jQuery Traversing: Siblings

Siblings are elements with the same parent. jQuery has methods to move sideways between them.

<ul id="list">
  <li>One</li>
  <li>Two</li>
  <li id="three">Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>
MethodReturns
.siblings()All siblings, except the element itself
.next()The next sibling
.nextAll()All next siblings
.nextUntil(sel)All next siblings until the selector (not included)
.prev()The previous sibling
.prevAll()All previous siblings (the nearest first)
.prevUntil(sel)All previous siblings until the selector
var text = function ($els) { return $els.map(function () { return $(this).text(); }).get().join(', '); };

console.log('siblings:  ' + text($('#three').siblings()));
console.log('next:      ' + text($('#three').next()));
console.log('nextAll:   ' + text($('#three').nextAll()));
console.log('prev:      ' + text($('#three').prev()));
console.log('prevAll:   ' + text($('#three').prevAll()));
Console output

siblings: One, Two, Four, Five
next: Four
nextAll: Four, Five
prev: Two
prevAll: Two, One

Look at prevAll(): the nearest sibling “Two” comes first, then “One”.

Filter by a selector

<div id="wrap">
  <h3>Title</h3>
  <p class="intro">Intro</p>
  <p>Text 1</p>
  <p>Text 2</p>
  <h3 id="second">Second title</h3>
  <p>Text 3</p>
</div>
console.log($('h3').first().nextAll('p').length);
console.log($('h3').first().nextUntil('h3').length);
console.log($('.intro').siblings('p').length);
Console output

4
3
3

nextUntil('h3') is great to get all the elements of one section, until the next heading.

Example: highlight the clicked item and reset the others

<ul id="tabs">
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul>
$('#tabs li').on('click', function () {
  $(this).addClass('on').siblings().removeClass('on');
});

$('#tabs li').eq(0).click();
$('#tabs li').eq(2).click();
HTML after the code runs

<ul id="tabs">
<li class="">Tab 1</li>
<li>Tab 2</li>
<li class="on">Tab 3</li>
</ul>

Note: Use siblings() for “all others”, and next() and prev() for sliders and step by step forms. Next: Traversing: Filtering.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write jQuery code to count the items of a list
Write jQuery code to find the total of a table column
Write jQuery code to add alternate row colors to a table
Interview Questions & Answers
What are jQuery selectors?
What is the difference between find() and children() in jQuery?
What is the difference between parent(), parents() and closest() in jQuery?
How do you check if an element exists in jQuery?
What is the difference between this and $(this) in jQuery?
What is the use of end() in jQuery?