.parentsUntil()

.parentsUntil( [ selector ] ) Returns: jQuery

Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

  • version added: 1.4.parentsUntil( [ selector ] )

    selectorA string containing a selector expression to indicate where to stop matching ancestor elements.

Given a jQuery object that represents a set of DOM elements, the .parentsUntil() method traverses through the ancestors of these elements until it reaches an element matched by the selector passed in the method's argument. The resulting jQuery object contains all of the ancestors up to but not including the one matched by the .parentsUntil() selector. Consider a page with a basic nested list as follows:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item A, we can find its ancestors up to but not including <ul class="level-1"> as follows:

$('li.item-a').parentsUntil('.level-1')
    .css('background-color', 'red');

The result of this call is a red background for the level-2 list and the item II.

If the .parentsUntil() selector is not matched, or if no selector is supplied, the returned jQuery object contains all of the previous jQuery object's ancestors. For example, let's say we begin at item A again, but this time we use a selector that is not matched by any of its ancestors:

$('li.item-a').parentsUntil('.not-here')
    .css('background-color', 'red');

The result of this call is a red background-color style applied to the level-2 list, the item II, the level-1 list, the <body> element, and the <html> element.

Example:

Find the ancestors of <li class="item-a"> up to <ul class="level-1"> and give them a red background color.

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>
<script>
    $('li.item-a').parentsUntil('.level-1')
      .css('background-color', 'red');
</script>
</body>
</html>

Demo: