Cover Image for jQuery closest() method
100 views

jQuery closest() method

The closest() method in jQuery is used to search for the closest ancestor element that matches a given selector. It starts with the current element and travels up the DOM tree, examining each parent element until a match is found.

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

$(selector).closest(selector)

Parameters:

  • selector: The selector to match the closest ancestor element against.

Return Value:
The closest() method returns a jQuery object containing the closest ancestor element that matches the specified selector. If no match is found, it returns an empty jQuery object (i.e., with a length of 0).

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery closest() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .selected {
            border: 2px solid red;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner">
            <p>This is a paragraph inside the inner div.</p>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // Select the paragraph element and find its closest ancestor with class "outer"
            var closestOuterDiv = $("p").closest(".outer");

            // Add a border to the closest ancestor with class "outer"
            closestOuterDiv.addClass("selected");
        });
    </script>
</body>
</html>

In this example, we have an HTML structure with a paragraph (<p>) element inside a nested div hierarchy. We use the closest() method to find the closest ancestor element with class “outer” starting from the paragraph element. Once the closest ancestor is found, we add the class “selected” to it, giving it a red border.

Keep in mind that closest() only looks at ancestor elements (parents, grandparents, etc.) and does not search through sibling or descendant elements. If you need to search for elements at the same level or among siblings, you can use other jQuery traversal methods such as siblings(), prev(), next(), etc.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS