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 the search.

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

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.

Example of jQuery Closest Method with Filter & DOM Condition

Now consider the below HTML. There is a li with id dom and 2 ul elements with class 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" });

DEMO DOWNLOAD

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.