Reputation: 46477
How do I select the next "n" elements starting from the current element? What I mean is...
$(this).attr(...);
I want to do this "n" times. For the example of n=4:
$(this).attr(...);
$(this).next().attr(...);
$(this).next().next().attr(...);
$(this).next().next().next().attr(...);
or perhaps do it in a loop:
for (i = 0; i < n; i++) {
$(this).next().attr(...);
}
How can I do this? Is there a way I can do this by selecting the next "n" elements or in a loop?
Upvotes: 50
Views: 17262
Reputation: 18185
This should work:
$(this).nextAll().slice(0,4).attr(…)
Update:
This will work, too:
$(this).nextAll("*:lt(4)").attr(…)
Upvotes: 71
Reputation: 10071
the nextAll
method selects the following siblings of an element, optionally filtered by a selector. You could then follow that with a slice
to restrict to a smaller n.
Upvotes: 10
Reputation: 6109
$(this).slice(start_index, end_index)
will select a portion of your selection. You could keep track of your current index in the loop and then apply the .slice(cur_index, cur_index+n)
function on the original set when you hit your condition.
Upvotes: 0