I have a DOM like this;
<li></li>
<li class="this"></li>
<li class="this"></li>
<li></li>
<li></li>
<li class="this"></li>
<li class="this"></li>
<li class="this"></li>
<li></li>
<li class="this"></li>
<li></li>
<li></li>
I would only like to select the first li within each series of consecutive thises.
So, if I would for instance apply a .addClass("that") to the objects of this selector, the resulting DOM would look like so;
<li></li>
<li class="this that"></li>
<li class="this"></li>
<li></li>
<li></li>
<li class="this that"></li>
<li class="this"></li>
<li class="this"></li>
<li></li>
<li class="this that"></li>
<li></li>
<li></li>
What would be the most efficient way of achieving such an effect? I cannot add or remove any elements in the DOM (so for instance wrapping the consecutive series in their own wrapper divs is not possible).
Thanks a lot in advance!
Will this work?
$("li:not(.this) + .this").addClass('that');
EDIT: If the first item is of class this, that won't work, you'll need this (if it applies):
$("li:not(.this) + .this, .this:first-of-type").addClass('that');
$('.this').each(function(){
if($(this).prev().hasClass('this')==false){
$(this).addClass('that');
}
});
loop through all elements with the class this and if its previous sibling doesn't have a the same class then add that to it
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