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?
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.
This should work:
$(this).nextAll().slice(0,4).attr(…)
Update:
This will work, too:
$(this).nextAll("*:lt(4)").attr(…)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With