Current element

How to get an element with a class after the current one in jQuery?

Here is an example html code:

<div id="current_element">Current element</div>
Many unknown tags...
<div class="target">This is target element</div>
Many other tags...

Note. The target element and the current element may not be under the same parent, so I cannot find it with .nextAll ('. Target'), right?

Is there a simple way to find it? Thank!

+3
source share
2 answers

You html in the comment is different from the one asked 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 wrap their 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 will return and find another child:

//this = .current_element
var $target = $(this).closest("#mainparent").find(".target");

Hope this helps!

+2
source

Since elemenets are returned in document order, you can use .index()to find the following in a collection containing both, for example:

var ce = $("#current_element"), all = $("#current_element, .target");
var target = all.eq(all.index(ce)+1);

You can check it out here .

+10
source

Source: https://habr.com/ru/post/1771649/


All Articles