How to get an element with class after current one in JQuery?
Here is the sample html code:
<div id="current_element">Current element</div>
Many unknown tags...
<div class="target">This is target element</div>
Many other tags...
Note That Target element and current element may not under the same parent, so I can't find it with .nextAll('.target'), right?
Are there any simple way to开发者_如何学Go find it? Thanks!
Since elemenets are returned in document order, you can use .index()
to find the next one in a set containing both, like this:
var ce = $("#current_element"), all = $("#current_element, .target");
var target = all.eq(all.index(ce)+1);
You can test it out here.
You html in the comment is different to the one in the question
<div id="area1">
<div id="current_element">Current</div>
</div>
<div id="area2">
<div class="target">Target</div>
</div>
What I would do is to wrap them with a div:
<div id="mainparent">
<div id="area1">
<div id="current_element">Current</div>
</div>
<div id="area2">
<div class="target">Target</div>
</div>
<div>
Then I go back and find the other child:
//this = .current_element
var $target = $(this).closest("#mainparent").find(".target");
I hope this helps!
精彩评论