开发者

How to get an element with class after current one in JQuery?

开发者 https://www.devze.com 2023-01-21 08:58 出处:网络
Here is the sample html code: <div id=\"current_element\">Current element</div> Many unknown tags...

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消