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/.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With