Using sQuery to Interact with a BEM Accordion (jQuery for BEM)

Edmund Reed
2 min readJun 16, 2019

--

Full disclosure: I am the author of sQuery and this article is intended to promote the tool

If you don’t use a fancy JavaScript framework and still work directly on the DOM, perhaps you use BEM as a CSS naming convention. If you do, this article is for you.

Creating a basic accordion with vanilla JavaScript and something like Sass for styling doesn’t have to be inherently difficult, but it can be made easier with sQuery. Let’s start off by drafting the markup for an accordion, using BEM as a naming convention:

For the accordion to “work”, we will add a BEM modifier of ‘active’ to accordion panel elements when we want them to be “open”. So if the first panel in our accordion were open, the markup would be:

We will want this class to be toggled when the panel’s corresponding “title” element is clicked. This can be achieved with some fairly straightforward JavaScript:

This is about as basic as it gets with regards to building a BEM accordion with vanilla JavaScript; all we’re doing is toggling a CSS class on one div when another div is clicked. Whilst there’s not really much wrong with the above code, in projects that use BEM with custom JavaScript, there’s going to be a lot of DOM querying to find blocks and elements in order to toggle modifiers, which is why sQuery exists. With sQuery, the above functionality can be reduced to:

By identifying and abstracting BEM querying and manipulating into its own API, your code can become much more succinct and readable, improving things like maintainability and scalability. You’ll notice that no client-side keywords are repeated in the sQuery example; the strings ‘accordion’, ‘panel’ and ‘title’ all only appear just the once. In the vanilla example there were several repetitions. Again, this could easily be handled with some simple vanilla JavaScript, but doing so only adds to the verboseness of the code.

Sign me up!

First step is to get sQuery installed:

npm install --save @onenexus/squery

…and then imported:

import sQuery from '@onenexus/squery';

Finally, it needs to be initialised with the BEM preset:

sQuery.init({ preset: 'BEM' });

Checkout the sQuery Wiki for more examples and documentation

And that’s it! Our sQuery code will now work. Happy coding!

--

--

Edmund Reed

Design Systems Architect 🎨 UI•UX designer & developer 💻 I take front-end thought experiments too far 🧪 @valtech 💙