jQuery Traversal - nextAll() Method
Example
Find the first div after all class names and add them the class name:
$("div:first").nextAll().addClass("after");
Definition and Usage
nextAll() gets all following sibling elements of each element in the matching element collection, with the selection by selector being optional.
Syntax
.nextAll(selector)
Parameter | Description |
---|---|
selector | String value, containing the selector expression used to match elements. |
Detailed Explanation
If a jQuery object representing a set of DOM elements is given, the .nextAll() method allows us to search for the following sibling elements in the DOM tree and construct a new jQuery object with matching elements.
This method accepts an optional selector expression, of the same type as the one I pass to the $() function. If a selector is applied, it will filter them by checking if the elements match.
Think about the following page with a simple list:
<ul> <li>list item 1</li> <li>list item 2</li> <li class="third-item">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
If we start from item 3, then we can find the elements that appear after it:
$('li.third-item').nextAll().css('background-color', 'red');
The result of this call is that projects 4 and 5 have been set to red background. Since we did not apply a selector expression, the following element is clearly included as part of the object. If we had already applied a selector, it would be checked for a match before including it.