How to Get All Sibling Elements in jQuery
This article explains how to select and manipulate sibling elements
in the Document Object Model (DOM) using jQuery. You will learn about
the primary .siblings() method, its syntax, how to apply
optional filtering selectors, and how to use it in practical web
development scenarios.
The primary jQuery method used to get all sibling elements of a
selected element is .siblings(). A sibling is any element
that shares the same direct parent in the DOM tree. When called on a
target element, .siblings() traverses forward and backward
along the DOM tree to return every neighboring element, excluding the
original element itself.
Syntax and Basic Usage
The basic syntax for the method is:
$(selector).siblings([filter]);When used without arguments, it returns all sibling elements:
// Selects all siblings of the element with the ID "target"
$('#target').siblings().css('opacity', '0.5');Filtering Sibling Elements
The .siblings() method accepts an optional selector
expression as an argument. Passing a selector filters the returned set
to include only siblings that match that specific criteria.
// Selects only sibling elements that have the class "highlight"
$('#target').siblings('.highlight').addClass('active');
// Selects only sibling <span> elements
$('#target').siblings('span').hide();Practical Example
Consider the following HTML list:
<ul>
<li>Apple</li>
<li id="selected-item">Banana</li>
<li class="citrus">Orange</li>
<li class="citrus">Lemon</li>
</ul>To modify the sibling elements using jQuery:
$(document).ready(function() {
// Returns Orange, Lemon, and Apple (excludes Banana)
$('#selected-item').siblings().addClass('unselected');
// Returns only Orange and Lemon
$('#selected-item').siblings('.citrus').css('color', 'orange');
});Key Differences from Other Traversal Methods
Unlike .next() or .prev(), which only
return the immediately adjacent element in one direction,
.siblings() selects all matching elements on the same
hierarchical level regardless of whether they appear before or after the
target element in the document source.