How to Get the Next Sibling Using jQuery next()

This article provides a direct guide on how to target and retrieve the immediately following sibling of a DOM element using the jQuery next() method. You will learn the basic syntax, see practical HTML and JavaScript examples, and understand how to apply optional selector filters to target specific adjacent elements.

Understanding the jQuery next() Method

The jQuery .next() method travels down to the immediately following sibling element in the DOM tree. It only checks the single element directly after the selected element, ignoring any child elements, parent elements, or siblings further down the chain.

Basic Syntax

$(selector).next(filter);
  • selector: The element from which you begin DOM traversal.
  • filter (optional): A string containing a selector expression to verify the sibling matches before selecting it.

Basic Example

Consider the following HTML list structure:

<ul>
  <li class="first-item">Apples</li>
  <li>Bananas</li>
  <li>Oranges</li>
</ul>

To select "Bananas" (the sibling immediately following "Apples") and change its text color, use:

$('.first-item').next().css('color', 'red');

In this case, jQuery targets .first-item, moves immediately to the next element (<li>Bananas</li>), and applies the red text color.

Using an Optional Filter

You can provide a selector as an argument to .next() to ensure the adjacent element matches a specific class, tag, or attribute.

Consider this updated HTML snippet:

<div class="active">Item 1</div>
<div class="highlight">Item 2</div>
<div>Item 3</div>

If you only want to style the next sibling if it has the class highlight:

$('.active').next('.highlight').css('font-weight', 'bold');

Because Item 2 immediately follows Item 1 and has the .highlight class, the style is applied. If Item 2 did not have the .highlight class, .next('.highlight') would return an empty jQuery set, even if Item 3 matched the class.

Key Considerations

  • Only One Sibling: The .next() method only targets the single immediately following element. If you need to select all subsequent siblings, use .nextAll() instead.
  • Non-Element Nodes: jQuery's .next() only targets element nodes; text and comment nodes are automatically ignored during traversal.