.closest() methodThe .closest(selector) method in jQuery is used to find the first element from the matched elements set and their ancestors,which matches the selector.
.closest() method Syntax.closest(selector) .closest(selector[,context]) .closest(selection) .closest(element) .closest(selectors[,context])
.closest() method ExampleBegins with the current element,searches through their ancestors step by step,return the first matching elements.
Finds closest matching element and highlight them.
HTML
<ul>
<li class="category">Language
<ul>
<li class="lang">Java
<ul>
<li>Java tutorial</li>
<li>Java Examples</li>
</ul>
</li>
<li class="lang">Python
<ul id="python">
<li>Python tutorial</li>
<li id="pyex">Python Examples</li>
</ul>
</li>
</ul>
</li>
<li class="category">Tools</li>
<li class="category">Lautturi</li>
</ul>
jQuery
$("#pyex").closest('li').css('background','cyan');
// [<li id="pyex">]
$("#pyex").closest('.lang').css('background','cyan');
// [<li class="lang">]
var python = document.getElementById( "python" );
$("#pyex").closest(python).css('background','cyan');
// [<ul id="python">]
var category = $( ".category" );
$("#pyex").closest(category).css('background','cyan');
// [<li class="category">Language]
$("#pyex").closest(['.lang','body']).css('background','cyan');
// [<li class="lang">,<body>]
