Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Find next element that is not a sibling

Let's say I have following HTML:

<span>     <span id="x1" class="x">X1</span> </span> <span>     <span>         <span id="x2" class="x">X2</span>     </span> </span> 

And $(this) is the <span id="x1" ...>.

What is the best way to find next element matching .x with jQuery?
The structure of the actual document is unpredictable, so the HTML provided is only an example.

I can't use nextAll as it only finds siblings.
If I do $('.x'), it finds all, but I'll have to iterate/compare.
Is there a better solution?

See also: http://jsfiddle.net/JZ9VW/1/.

like image 773
Andrey Shchekin Avatar asked Dec 26 '12 01:12

Andrey Shchekin


People also ask

How to get the next element in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

Is visible function in jQuery?

The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.

Which of the following methods returns a reference to the next child of the current element's parent?

The read-only nextSibling property of the Node interface returns the node immediately following the specified one in their parent's childNodes , or returns null if the specified node is the last child in the parent element.


1 Answers

Select all elements with class x, calculate the index of the current element and get the element with the index + 1:

var $x = $('.x'); var $next = $x.eq($x.index(this) + 1); 

This works because elements are selected in document order. You only have to select all .x elements once on page load (if they are not dynamically created).

like image 84
Felix Kling Avatar answered Sep 21 '22 18:09

Felix Kling