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 :not
selector @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 :not
selector prematurely.
http://jsbin.com/umivas/6/edit
.class1 ~ .class2 + .class2 {
color: red;
}
.class1 + .class2 {
color: red;
}
.class1 ~ *:not(.class2) ~ .class2 {
color: inherit;
}
Edit: Sorry for the lack of explanation. The last part attempts to select any element that is a sibling of .class1
that doesn't have .class2
and resets all subsequent siblings with .class2
back to their original state. This could be kind of insane depending on how many styles you're applying.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With