TExcelTAD
Home › jQuery › jQuery Siblings

jQuery Traversing: Siblings

Siblings share the same parent. jQuery can move sideways in both directions — to the next or previous element, to all following or preceding elements, or to every sibling at once.

Method Returns
.siblings(sel?) All siblings (not the element itself)
.next(sel?) The immediately following sibling (if it matches sel)
.nextAll(sel?) All following siblings
.nextUntil(stop, sel?) Following siblings up to, not including, stop
.prev(sel?) The immediately preceding sibling
.prevAll(sel?) All preceding siblings, nearest first
.prevUntil(stop, sel?) Preceding siblings up to, not including, stop

Try every method

Click a box to choose the starting element, then press a method button.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 13px; }
    #row span { display: inline-block; width: 34px; height: 34px; line-height: 34px; text-align: center;
                margin: 2px; background: #e3e9ef; border-radius: 4px; cursor: pointer; }
    #row span.start { background: #e67e22; color: #fff; }
    #row span.hl { background: #0769ad; color: #fff; }
    #row span.stop { outline: 2px dashed #c0392b; }
  </style>
</head>
<body>
  <div id="row">
    <span>1</span><span>2</span><span>3</span><span class="stop">4</span><span>5</span><span class="start">6</span><span>7</span><span class="stop">8</span><span>9</span>
  </div>
  <p>
    <button>siblings</button> <button>next</button> <button>nextAll</button> <button>nextUntil</button><br>
    <button>prev</button> <button>prevAll</button> <button>prevUntil</button>
  </p>
  <small>Orange = start, dashed = <code>.stop</code> elements (used by the Until methods)</small>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#row span").on("click", function () {
      $("#row span").removeClass("start hl");
      $(this).addClass("start");
    });

    $("button").on("click", function () {
      const method = $(this).text();
      const $start = $("#row .start");
      const $result = method.endsWith("Until") ? $start[method](".stop") : $start[method]();
      $("#row span").removeClass("hl");
      $result.addClass("hl");
      console.log(method + "():", $result.map((i, el) => $(el).text()).get().join(", ") || "(empty)");
    });
  </script>
</body>
</html>

$start[method]() calls the method whose name is in the variable — $start["nextAll"]() is the same as $start.nextAll().

next() with a selector is a test, not a search

A common surprise: .next(".panel") does not search forward for the next .panel. It looks at the immediately following sibling and keeps it only if it matches. To search forward, use .nextAll(".panel").first():

js
// <h3>…</h3> <p>intro</p> <div class="panel">…</div>
$("h3").next(".panel");                // empty! the next sibling is the <p>
$("h3").nextAll(".panel").first();     // the div.panel

A step-by-step wizard

.next() and .prev() are ideal for sequences such as slideshows or multi-step forms:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .step { display: none; padding: 16px; border: 1px solid #0769ad; border-radius: 8px; width: 260px; min-height: 60px; }
    .step.current { display: block; }
    #dots span { display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: #ccc; margin: 6px 3px; }
    #dots span.on { background: #0769ad; }
  </style>
</head>
<body>
  <div id="wizard">
    <div class="step current">Step 1: Choose a plan</div>
    <div class="step">Step 2: Enter your details</div>
    <div class="step">Step 3: Payment</div>
    <div class="step">Step 4: Done 🎉</div>
  </div>
  <div id="dots"></div>
  <button id="prev">◀ Back</button>
  <button id="next">Next ▶</button>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const $steps = $("#wizard .step");
    $steps.each(() => $("#dots").append("<span>"));

    function render() {
      const $cur = $steps.filter(".current");
      const i = $cur.index();
      $("#dots span").removeClass("on").eq(i).addClass("on");
      $("#prev").prop("disabled", $cur.prev().length === 0);
      $("#next").prop("disabled", $cur.next().length === 0);
      console.log("step", i + 1, "of", $steps.length);
    }

    $("#next").on("click", function () {
      $steps.filter(".current").removeClass("current").next().addClass("current");
      render();
    });
    $("#prev").on("click", function () {
      $steps.filter(".current").removeClass("current").prev().addClass("current");
      render();
    });
    render();
  </script>
</body>
</html>

.prev().length === 0 tells you that you are at the first step, so the Back button is disabled.

Highlighting a star rating

.prevAll() and .nextAll() make rating widgets easy: hovering a star fills it and all stars before it.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .stars span { font-size: 32px; color: #ccc; cursor: pointer; }
    .stars span.on { color: #f5b301; }
  </style>
</head>
<body>
  <div class="stars"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
  <p id="rating">Not rated</p>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    let rating = 0;
    const $stars = $(".stars span");
    function paint(n) { $stars.removeClass("on").slice(0, n).addClass("on"); }

    $stars.on("mouseenter", function () {
      $(this).addClass("on").prevAll().addClass("on");
      $(this).nextAll().removeClass("on");
    }).on("click", function () {
      rating = $(this).index() + 1;
      $("#rating").text("You rated " + rating + " / 5");
      console.log("rating:", rating);
    });
    $(".stars").on("mouseleave", () => paint(rating));
  </script>
</body>
</html>

Note: Sibling methods only see element siblings. Text nodes and comments between elements are skipped.

Test yourself

Does .siblings() include the element itself?

  1. Yes
  2. No
  3. Only if it matches the selector
  4. Only for the first element

The element after an h3 is a <p>, followed by a div.panel. What does $("h3").next(".panel") return?

  1. The div.panel
  2. The p
  3. An empty set
  4. Both

Which method returns all following siblings up to, but not including, an element matching .stop?

  1. .nextAll(".stop")
  2. .nextUntil(".stop")
  3. .next(".stop")
  4. .siblings(".stop")