jQuery Introduction | Traversing Elements | Traversing Ancestor Elements .parents() .closest()

Traversing Ancestor Elements

Methods for traversing ancestor elements, including the parent element of a specific element in the DOM tree, are as follows.

Method Description
.parent() Selects the parent element of the selected element.
.parents() Selects all ancestor elements of the selected element.
.parentsUntil() Selects all ancestor elements of the selected element up to, but not including, the element matching the specified selector.
.closest() Selects the first element matching the specified selector among the selected element and its ancestors.

.parent() Method

The .parent() method selects the parent element of the selected element. You can also pass a selector as an argument to select only the parent element that matches the selector.

When HTML elements exist as follows:

<div>div (grandparent)
  <ul>ul (parent)
    <li>li (child)
        <span>span (grandchild)</span>
    </li>
  </ul>
</div>

Select the parent element of the <ul> element and change its CSS style.

$("ul").parent().css({"border": "2px solid red"});

.css() sets the style passed as an argument on the selected element.

Run code

.parents() Method

The .parents() method selects all ancestor elements of the selected element. You can also pass a selector as an argument to select only ancestor elements that match the selector.

Select all <div> elements among the ancestor elements of the <ul> element and change their CSS style.

$("ul").parents("div").css({"border": "2px solid red"});

Run code

.parentsUntil() Method

The .parentsUntil() method selects all ancestor elements of the selected element up to, but not including, the element matching the selector passed as an argument. If no selector is passed as an argument, it selects all ancestor elements of the selected element, like .parent().

Select all elements among the ancestors of the <li> element up to immediately before the first <div> element and change their CSS style.

$("li").parentsUntil("div").css({"border": "2px solid red"});

Run code

.closest() Method

The .closest() method selects the first element from the set of elements matching the selector passed as an argument among the selected element and its ancestors. Its traversal behavior is similar to .parents(), but it differs in that it searches not only the ancestor elements but also the selected element itself.

When HTML elements exist as follows:

<div>div (grandparent)
  <ul>ul (parent)
    <li class="me">li (child)
        <span>span (grandchild)</span>
    </li>
  </ul>
</div>

Select the first <li> element among the element with class "me" itself and its ancestors, then change its CSS style.

$(".me").closest("li").css({"border": "2px solid red"});

In this example, the selected element with class "me" is itself a <li> element, so only that element’s CSS style is changed.

Run code