jquery
  1. jquery-parents

JQuery parents()

The .parents() method in jQuery returns an array of all the ancestor elements of the selected element(s).

Syntax

The basic syntax of the .parents() method is:

$(selector).parents(filter)
  • selector: The element(s) to search for.
  • filter: An optional parameter that specifies a selector to filter the returned ancestor elements.

Use

The .parents() method can be used to traverse up the DOM tree and select all ancestor elements of the selected element(s). It's useful for finding specific parent elements of an element or for traversing up to a specific point in the DOM tree.

Example

<!DOCTYPE html>
<html>
<head>
    <title>jQuery parents() example</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <div class="grandparent">
        <div class="parent">
            <div class="child">
                Sample Text
            </div>
        </div>
    </div>
    
    <script>
        $(document).ready(function() {
            var ancestorElems = $(".child").parents();
            
            $(ancestorElems).css({"border": "1px solid black", "padding": "10px"})
            .children().css("color", "red");
        });
    </script>
</body>
</html>
Try Playground

In this example, we have a DOM tree with three nested div elements with classes "grandparent", "parent", and "child". We use the .parents() method to select all ancestor elements of the .child element and apply styling to them. We also select and modify the styles of any children elements of the ancestor elements.

Summary

The .parents() method in jQuery is a useful way to traverse up the DOM tree and select all ancestor elements of the selected element(s). It can be used to find specific parent elements or to traverse up to a specific point in the DOM tree. With the optional filter parameter, it's possible to further narrow down the selection of ancestors.

Published on: