How to Select All Following Siblings with jQuery
To select all elements following a specific sibling in the DOM tree,
jQuery provides dedicated traversal methods and selector combinators.
This article explains how to use the .nextAll() method and
the general sibling combinator (~) to target subsequent
siblings, filter the results, and manipulate DOM elements
efficiently.
Using the .nextAll()
Method
The primary and most flexible way to select all following siblings of
an element is using the .nextAll() method. This method
searches forward along the DOM tree to find every sibling element that
comes after the matched element.
Basic Syntax
$(selector).nextAll();Example
Consider the following HTML structure:
<ul>
<li>First item</li>
<li id="start">Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>To target and modify every item that appears after
#start:
$("#start").nextAll().css("color", "red");This code targets the third, fourth, and fifth
<li> elements and turns their text red.
Filtering Results with
.nextAll()
You can pass an optional selector expression to
.nextAll() to filter the returned siblings:
<div>
<p id="target">Reference paragraph</p>
<span class="highlight">Following span</span>
<p class="highlight">Following paragraph</p>
<p>Standard paragraph</p>
</div>// Selects only following <p> tags with the class "highlight"
$("#target").nextAll("p.highlight").css("font-weight", "bold");Using the General Sibling
Combinator (~)
Alternatively, you can achieve the same result using standard
CSS-style selectors directly inside the main $() function
with the general sibling combinator (~).
Syntax
$("prev ~ siblings")Example
// Selects all <li> elements that follow the #start element
$("#start ~ li").addClass("active");This approach is concise and useful when you do not need to perform operations on the initial element first.
Selecting a Range with
.nextUntil()
If you need to select following siblings only up to a certain point,
use the .nextUntil() method:
<div class="start">Start</div>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="stop">Stop</div>
<div class="item">Item 3</div>// Selects Item 1 and Item 2, stopping before .stop
$(".start").nextUntil(".stop").css("background", "yellow");Summary
Use .nextAll() when chaining multiple jQuery traversal
methods together or when dynamic filtering is needed. Use the
~ combinator for simple, declarative selections within a
single query string. Use .nextUntil() when you need bounded
selections between two specific elements.