Learn jQuery Closest Method – .closest() with Example and Codes

Learn jQuery Closest Method – .closest() with Example and Codes

If you want to find a parent, grandparent, great-grandparent, and so on, of an element then use jQuery Closest method. You can also provide the filter conditions to narrow down this search.

The .closest() method moves upwards from the selector all the way up to the document root.

Remember: This method returns only 0 or 1 element.

I hope you know the usage of jQuery Parents method. If not that visit this tutorial link.

Syntax of jQuery Closest Method

There are 2 syntaxes of this method.

  • 1. Returns the parent based on a filter condition.
    $(selector).closest(filter)
    
    
  • 2. Returns the parent based on filter condition and looking only inside the ‘DOM’ element.
    $(selector).closest(filter,dom)
    
    

Example of jQuery Closest Method with Filter Condition

Consider the below HTML of a page.

<ul>
    div (great-grandparent)
    <li>
        ul (second grandparent)
        <ul>
            ul (first grandparent)
            <li>
                li (direct parent)
                <span>span</span>
            </li>
        </ul>
    </li>
</ul>

When I execute – $(“span”).closest(“ul”), then the ul (first grandparent) element gets selected.

$("span").closest("ul").css({ "color": "orange", "border": "2px solid orange" });

So the above jQuery Closest code will turn the color of ul (first grandparent) to orange.

There is also a related tutorial on jQuery Siblings method which you will like to read.

Example of jQuery Closest Method with Filter & DOM Condition

Now consider the below HTML. There is a li with an id called dom, and 2 ul elements with class called parent.

<ul>
    div (great-grandparent)
    <li id="dom">
        Element with id "DOM" (second grandparent)
        <ul class="parent">
            ul with class ".parent" (first grandparent)
            <li class="parent">
                li with class ".parent" (direct parent)
                <span>span</span>
            </li>
        </ul>
    </li>
</ul>

I will use the DOM condition to find the parent only inside the ‘DOM’ selector.

So the below jQuery Closest code will turn the direct parent element to orange.

var item = document.getElementById("dom");
$("#span2").closest(".parent", item).css({ "color": "orange", "border": "2px solid orange" });

Refer the DEMO & DOWNLOAD Code links:

DEMO DOWNLOAD

Next tutorial: Learn how to correctly use the jQuery Children method for DOM manipulations.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.