jquery
  1. jquery-parentsuntil

JQuery parentsUntil()

The parentsUntil() method in JQuery allows you to select all the ancestor elements between two given elements. This can be useful for selecting all the parent elements of an element up to a certain level.

Syntax

The syntax for the parentsUntil() method is as follows:

$(selector).parentsUntil(filter, expression)
  • selector: the selector that specifies the child element(s) to find the parent(s) of.
  • filter: the optional selector that specifies the parent element(s) to stop at.
  • expression: the optional expression used to filter the parent elements that are found.

Use

The parentsUntil() method in JQuery is useful for when you need to select all the ancestor elements of an element up to a certain level. For example, if you have a nested list with multiple levels, you may want to select all the parent ul elements of a given li element up to a certain level.

Example

Here is an example of using the parentsUntil() method in JQuery:

<ul>
  <li>Item 1</li>
  <li class="selected">Item 2
    <ul>
      <li>Subitem 1</li>
      <li class="sub-selected">Subitem 2
        <ul>
          <li>Sub-subitem 1</li>
          <li>Sub-subitem 2</li>
        </ul>
      </li>
      <li>Subitem 3</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

In this example, we have a nested list with multiple levels. The selected class has been applied to the second li element, and the sub-selected class has been applied to the second li element within the nested list.

Here is some JQuery code that selects all the parent ul elements of the .sub-selected element up to the ul containing the .selected element:

$(".sub-selected").parentsUntil(".selected", "ul").css("background-color", "yellow");


<!DOCTYPE html>
<html>
<head>
    <title>jQuery parent() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
</head>
<body>
   <ul>
  <li>Item 1</li>
  <li class="selected">Item 2
    <ul>
      <li>Subitem 1</li>
      <li class="sub-selected">Subitem 2
        <ul>
          <li>Sub-subitem 1</li>
          <li>Sub-subitem 2</li>
        </ul>
      </li>
      <li>Subitem 3</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>


    <script>
    $(".sub-selected").parentsUntil(".selected", "ul").css("background-color", "yellow");

    </script>
</body>
</html>
Try Playground

This code selects all the parent ul elements of the .sub-selected element up to the ul containing the .selected element and sets their background color to yellow.

Summary

The parentsUntil() method in JQuery is a useful tool for selecting all the ancestor elements between two given elements. It allows you to easily select all the parent elements of a given element up to a certain level. This method can be used in a variety of situations where you need to navigate the DOM and select specific elements.

Published on: