简体   繁体   中英

jQuery next method alternative

jquery's next method is looking for next sibling. But i need next element which is not sibling. I just need to iterate next elements in selector. For example:

$('.wrapper .parent div').next(); // in here next method looks first element
// in selector and get next sibling of it.

What i want is next matched element in selector. Simply calling each method will provide it to me but i dont need to iterate whole collection.

slice method will help me iterate manualy by controlled me but providing slice parameters makes it harder to use.

What can be another solution.

If you have a jQuery selector with multiple objects in it, there are a number of ways you can iterate or get individual elements in that list.

This tells you how many are in the collection:

$('.wrapper .parent div').length

This gets you the HTML DOM element for any item in the collection (depending upon what number you pass as the parameter to get() :

$('.wrapper .parent div').get(0);

This gets you a jQuery object for any item in the collection (depending upon what number you pass as the parameter to eq() :

$('.wrapper .parent div').eq(0);

You can iterate through the whole collection several ways. You can use .each() :

$('.wrapper .parent div').each(function(index) {
    // "this" will be set to the DOM element you are iterating in the collection
});

Or, you can iterate manually several different ways:

var items = $('.wrapper .parent div');
for (var i = 0; i < items.length; i++) {
    // items.get(i) is the DOM element
}

Or, you can even just convert the object into an array of DOM elements:

var domArray = $('.wrapper .parent div').makeArray();
for (var i = 0; i < domArray.length; i++) {
    // domArray[i] is the DOM element
}

Use jQuery eq method and pass the index to it. It Reduces the set of matched elements to the one at the specified index.

$('.wrapper .parent div').eq(1);//Whatever index you need pass into it. It is 0 based.

http://api.jquery.com/eq/

Perhaps try $(".wrapper .parent div:nth-child(2)") instead?

Or $(".wrapper .parent div:nth-child(" + i++ + ")") for the next-in-set functionality, where i is the first one you want to get.

JQuery nth-child selector documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM