当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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?

网友答案:

.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')
网友答案:

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');
网友答案:

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.

网友答案:

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).

分享给朋友:
您可能感兴趣的文章:
随机阅读: