Reputation: 15
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
});
Upvotes: 0
Views: 58
Reputation: 28611
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
}
});
Upvotes: 0
Reputation: 4919
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.
Upvotes: 1