Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - select the next item of this in each() function

Tags:

jquery

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>
like image 780
angry kiwi Avatar asked Jul 16 '11 05:07

angry kiwi


People also ask

How do I target the next class 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.

What is the use of jQuery each () function?

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.

What does .next do in jQuery?

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.

What is $() in jQuery?

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)


1 Answers

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.

like image 54
karim79 Avatar answered Oct 19 '22 20:10

karim79