I’ve got a project wherein I have no control whatsoever over the markup. I’m looking for a way to select every instance of ‘class2’ that immediately follows an instance of ‘class1’. The following strategy works, but in some cases there are over 20 instances of ‘class2’ in a row and I’d prefer to avoid that huge mess in my code.
.class1 + .class2,
.class1 + .class2 + .class2,
.class1 + .class2 + .class2 + .class2,
.class1 + .class2 + .class2 + .class2 + .class2,
.class1 + .class2 + .class2 + .class2 + .class2 + .class2
// etc.
{
// Applied Styles
}
…to style the following
<div class="class1"></div>
<div class="class2">Style Me!</div>
<div class="class2">Style Me!</div>
<div class="class2">Style Me!</div>
<div class="class2">Style Me!</div>
<p>Blah blah blah</p>
<div class="class2">DO NOT STYLE ME</div>
<div class="class2">DO NOT STYLE ME EITHER</div>
Here’s a stab in the dark using the new
:notselector @spudley suggested. It looks like it has okay support: http://caniuse.com/#search=%3Anot. I hope the syntax is right. Edits welcome.And most of this was taken from @mookamafoob’s solution. I didn’t submit an edit in case @mookamafoob was averse to using the
:notselector prematurely.http://jsbin.com/umivas/6/edit
Edit: Sorry for the lack of explanation. The last part attempts to select any element that is a sibling of
.class1that doesn’t have.class2and resets all subsequent siblings with.class2back to their original state. This could be kind of insane depending on how many styles you’re applying.