Cover Image for jQuery parent() method
90 views

jQuery parent() method

The jQuery parent() method is used to select the direct parent element of the matched element(s). It allows you to traverse up the DOM tree and select the immediate parent of the selected element(s).

Here’s the basic syntax of the parent() method:

$(selector).parent()

Parameters:

  • selector: (Optional) A selector string representing a filter that the parent element(s) must match to be selected. If specified, only parent elements matching the selector will be selected.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery parent() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="outer">
        <div id="inner">
            <p>This is the inner content.</p>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // Select the parent of the paragraph element
            var parentDiv = $("p").parent();

            // Add a class to the parent div
            parentDiv.addClass("highlight");
        });
    </script>
</body>
</html>

In this example, we have an outer <div> with the ID “outer” containing an inner <div> with the ID “inner,” which, in turn, contains a paragraph element. We use the parent() method to select the immediate parent of the paragraph element. We then add a class “highlight” to the selected parent div. As a result, the immediate parent div of the paragraph will have the “highlight” class applied to it.

You can use the parent() method to access and manipulate the immediate parent elements of selected elements. If you want to traverse multiple levels up the DOM tree, you can chain the parent() method with additional traversing methods like parents() or closest().

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS