Siblings

Select elements that share the same parent.

Syntax$(selector).siblings(); $(selector).next(); $(selector).prev();

Sibling methods move sideways among elements with the same parent:

  • .siblings() — all siblings.
  • .next() / .prev() — the immediately following / preceding sibling.

This is the classic pattern for “highlight the clicked item, dim the rest.”

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A tab navigation uses .siblings() to remove the .active class from all other tabs when one is clicked.
  • A star-rating widget applies a style to the clicked star and all its previous siblings to fill the rating.
  • An accordion removes the .open class from all sibling panels before opening the selected one.

More examples

Deactivate sibling tabs

.siblings() selects every sibling matching the filter, removing the .active class from all non-clicked tabs.

Example · html
<ul id="tabs">
  <li class="tab active">Tab 1</li>
  <li class="tab">Tab 2</li>
  <li class="tab">Tab 3</li>
</ul>
<script>
$(function () {
  $(".tab").click(function () {
    $(this).addClass("active").siblings(".tab").removeClass("active");
  });
});
</script>

Select only the next sibling

.next(".a") selects only the immediately following sibling that matches the class, powering the accordion.

Example · html
<div class="acc">
  <h4 class="q">Section 1</h4>
  <div class="a" style="display:none;">Content 1</div>
  <h4 class="q">Section 2</h4>
  <div class="a" style="display:none;">Content 2</div>
</div>
<script>
$(function () {
  $(".q").click(function () {
    $(this).next(".a").slideToggle(300);
  });
});
</script>

Select preceding siblings for star rating

.prevAll() selects all preceding siblings so clicking a star fills it and all stars to its left.

Example · html
<div id="stars">
  <span class="star" data-val="1">&#9733;</span>
  <span class="star" data-val="2">&#9733;</span>
  <span class="star" data-val="3">&#9733;</span>
  <span class="star" data-val="4">&#9733;</span>
  <span class="star" data-val="5">&#9733;</span>
</div>
<script>
$(function () {
  $(".star").click(function () {
    $(this).css("color", "gold")
      .prevAll(".star").css("color", "gold");
    $(this).nextAll(".star").css("color", "#ccc");
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.