views:

58

answers:

3

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?

Thanks.

A: 

$(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.

Ian Wetherbee
+7  A: 

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.

DDaviesBrackett
This is the way to go.
Stefan Kendall
+4  A: 

This should work:

$(this).nextAll().slice(0,4).attr(…)

Update:

This will work, too:

$(this).nextAll("*:lt(4)").attr(…)
jigfox
would the '0' in slice() be $(this)?
Hristo
no, because before that you call `.nextAll()` this doesn't contain the element itself
jigfox
Ahh that makes sense. Thanks!
Hristo
@Hristo - If you need the original one as well, you could call `$(this).nextAll().andSelf()...`.
patrick dw
@patrick... Thanks!
Hristo
@jigfox... is .slice() inclusive or exclusive on the parameters?
Hristo
+1 for the an alternate way to select other than slice.
Stefan Kendall
@Hristo: the first parameter is inclusive, the second exclusive
jigfox
@jigfox... Thanks!
Hristo