Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the next "n" elements starting from the current element in jQuery?

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?

like image 550
Hristo Avatar asked Aug 11 '10 19:08

Hristo


People also ask

What is the correct way of selecting the current element with jQuery selectors?

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.

How can I get next sibling in jQuery?

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.

How do I iterate through a div in jQuery?

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.


2 Answers

This should work:

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

Update:

This will work, too:

$(this).nextAll("*:lt(4)").attr(…)
like image 155
jigfox Avatar answered Oct 19 '22 12:10

jigfox


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.

like image 23
Dan Davies Brackett Avatar answered Oct 19 '22 11:10

Dan Davies Brackett