Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first in a subset

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!

like image 785
Emphram Stavanger Avatar asked Sep 08 '26 08:09

Emphram Stavanger


2 Answers

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');
like image 182
Ry- Avatar answered Sep 11 '26 00:09

Ry-


$('.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

like image 42
Moin Zaman Avatar answered Sep 11 '26 01:09

Moin Zaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!