Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Get next element with class (while ommitting others)

I have this code:

var toLoad = $('.sidebar').find('.active').next('li.list-element').attr('data-id');

Which should detect the next element after my .active with list-element class. It doesn't. The problem is, I have a list like this:

<li class="list-element active">...</li>
<li class="list-element">...</li>
<li class="ads">...</li>
<li class="list-element">...</li>
<li class="list-element">...</li>

And when I get to ads, my script stops. What can I do?

Upvotes: 0

Views: 1090

Answers (4)

philnash
philnash

Reputation: 73029

So, when you write

$('.sidebar').find('.active')

That will find one element, the li with the class active and .next() can only select from within that group.

You could, however, use just one CSS selector to find the next element from the .active one like so:

$('.sidebar .active ~ li.list-element:first').attr('data-id')

~ is the general sibling selector that matches elements that are after the original element (.active) and share a parent (.sidebar).

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388326

The problem is your understanding of the .next() method is wrong, it does not return the element element matching the selector, it will return the next sibling element only if it matches the passed selector

One easy solution is to find all the next elements then use the first one in the set

var toLoad = $('.sidebar').find('.active').nextAll('li.list-element:eq(0)').attr('data-id');

Upvotes: 2

Praveen Prasannan
Praveen Prasannan

Reputation: 7123

Jquery next()

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

.next() will only target the next element. You need to use .nextAll() along with :first or :eq(0) to target the next first sibling with the required class:

 var toLoad = $('.sidebar').find('.active').nextAll('li.list-element:first').attr('data-id')

Upvotes: 3

Related Questions