Sideways traversing allows you to find elements that are at the same level as the current element—those that share the same direct parent. This is incredibly useful for highlighting adjacent items in a menu, controlling siblings in a gallery, or managing form labels.
jQuery provides a total of seven methods for traversing sideways. We categorize them into "General," "Next," and "Previous."
| Method | What it returns... |
|---|---|
siblings() |
Returns all siblings of the selected element. |
next() |
Returns the very next sibling. |
nextAll() |
Returns all following siblings. |
nextUntil() |
Returns all siblings between two elements (ahead). |
prev(), prevAll(),
and prevUntil() work exactly like the "next" methods but search in the
opposite direction (backwards through the DOM).
Returns every element that shares the same parent as the target, except for the target itself. You can also pass a selector to filter specific siblings.
// Targets ALL brothers and sisters of h2
$("h2").siblings().css({"color": "red", "border": "2px solid red"});
// Targets only <p> siblings of h2
$("h2").siblings("p");
These are the most commonly used sibling methods. They only look at the one element directly above or below.
// Targets the very NEXT element after h2
$("h2").next().addClass("highlight");
// Targets the very PREVIOUS element before h2
$("h2").prev().fadeOut();
When you need to affect a large section of siblings, use nextAll() or
nextUntil().
// Targets every sibling AFTER h2 until the end of the parent
$("h2").nextAll();
// Targets everything BETWEEN h2 and h5
$("h2").nextUntil("h5");
A classic use case for next() is showing a hidden details box when a header
is clicked.
$(".accordion-header").click(function() {
// Find the very next element and slide it down
$(this).next(".accordion-content").slideToggle();
// Optional: Close all other siblings
$(this).siblings(".accordion-header").next(".accordion-content").slideUp();
});
next() are much safer than trying to
use IDs for every element in a recurring list (like blog comments or forum posts).