简体   繁体   中英

Accessing the previous element in $('.class').each()

Is there a way to access the previous or next element while in a certain iteration of a $('.class').each() loop; Where the elements with class 'class' are not siblings?

I was able to do this by traversing through the DOM tree. But I was wondering if there is a more concrete and elegant solution.

Current code:

$('.slider-range').each(function(index){
  var temp = $(this).closest('.panel').next('.panel').find('.slider-range');        
  //do something with temp
});

You will have to "store" the "selected" items in a variable and use the index passed to the callback like this:

var range = $('.slider-range');
range.each(function(index){
    var temp = index > 0 ? range[index - 1] : null;        
    //do something with temp
});

I added a condition on the value of the index, to make the temp variable null if index is 0 .

Edit: Corrected with index - 1 to "select" the previous item.

In your loop, you have access to the current index within the collection of jquery objects.

$('.slider-range').each(function(index){
  var temp = $(this).closest('.panel').next('.panel').find('.slider-range');        

  //do something with temp
});

You can use this to get any of the other items in that collection:

var items = $(".slider-range");
items.each(function(index) {
    if (index > 0)  {
        var prev = items[index-1];
        // do something with prev
    } 
});

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