oligofren oligofren - 1 month ago 6
CSS Question

Applying state changes that apply to many elements in a block

I like BEM a lot, and I usually use a variant of BEM where I use state classes to toggle sub-items on/off, leading to easy to understand rules in my SASS like:

.my-block{
&__element {
color : blue;

// I prefer state-classes over modifiers for state
&.is-selected { color : red; }

&--small { height: 50%; }
}
}


The problem I wonder how to solve in the most BEM-ish way is how to deal with a state change in my javascript that should apply to a lot of elements in a block. For instance, say I have a component that should hide or show different elements depending on whether you are in
step1
,
step2
or
step3
of a process.

The BEM bits are easy enough if I should just apply state classes on each of the elements, but that is just the problem. If I have 10 elements where 7 needs to be hidden on step 2 then that is 7x as much javascript to add as if I had just added a rules on the not so BEM-pure form of

&__element {
display: none;

// -- this --
.my-block.is-step4 & { display : block }
}


I could then activate all of those rules with one
myBlock.classList.toggle("is-step4")
, as opposed to one for each element.

My solution was a pragmatic middle point of developer convenience and pure BEM, but I wonder if there is a "pure" BEM solution that is also friendly in terms of line of codes needed in the javascript to update the elements?

Answer Source

Just use nested selectors for this case. So you'll have step modifiers on the parent block which contains all the rest of blocks you need to affect (and don't be afraid if such parent is the whole page).

See https://en.bem.info/methodology/faq/#can-i-use-nested-selectors — it's recommended solution.