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>
| Method | Returns |
|---|---|
.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 |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |