jQuery Traversing - next() Method
Example
Find the next sibling element of each paragraph and select only the paragraphs with the class name "selected":
$("p");.next(".selected");.css("background", "yellow");
Definition and Usage
The next() method gets the next sibling element of each element in the matching element collection. If a selector is provided, it retrieves the next sibling element that matches the selector.
Syntax
.next(selector)
Parameter | Description |
---|---|
selector | String value, containing the selector expression used to match elements. |
Detailed Explanation
If a jQuery object representing a collection of DOM elements is given, the .next() method allows us to search for the next sibling element in the DOM tree and construct a new jQuery object with the matching element.
This method accepts an optional selector expression, of the same type as the one I pass to the $() function. If the following sibling element matches the selector, it will remain in the newly constructed jQuery object; otherwise, it will be excluded.
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, we can find the elements that appear after it:
$('li.third-item');.next();.css('background-color', 'red');
The result of this call is that project 4 has been set to a 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.