I want to select the next element of this in each() function. check out the code comments
$(function(){
var selects = $('body').find('span');
selects.each(function(index,el){
if(index==0){
//remove the next span of this, which is span2
}
});
});
<body>
<div>
<span>1</span>
</div>
<span>2</span>
<div>
<span>3</span>
</div>
</body>
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 $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
next() method allows us to search through the immediately following sibling of these elements in the DOM tree and construct a new jQuery object from the matching elements. The method optionally accepts a selector expression of the same type that we can pass to the $() function.
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)
Based on your DOM structure, you can do:
var selects = $('body').find('span');
selects.each(function(index, el) {
if(index !== selects.length - 1) {
// select the next span
alert(selects.eq(index + 1).text());
}
});
You can try it here.
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