jQuery Traversal - 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");

Try it yourself

Definition and Usage

The next() method gets the immediately following 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 Description

If a jQuery object representing a collection of DOM elements is given, the .next() method allows us to search for the immediately following 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 immediately following sibling element matches the selector, it will remain in the newly constructed jQuery object; otherwise, it will be excluded.

Consider 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');

Try it yourself

The result of this call is that project 4 is set to a red background. Since we did not apply a selector expression, the element immediately following 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.