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.
There are 2 syntaxes of this method.
$(selector).closest(filter)
$(selector).closest(filter,dom)
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 are related tutorials –
1. jQuery Siblings method which you will like to read.
2. jQuery AJAX Example – Calling a C# Function With jQuery AJAX [With Code]
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 below DOWNLOAD link: