Home >>jQuery Tutorial >jQuery closest() Method
jQuery closest() method in jQuery is used to returns the first ancestor of the selected element and an ancestor is a parent, grandparent, great-grandparent, and so on.
Syntax:Return the first ancestor of the selected element: | $(selector).closest(filter) |
Return the first ancestor using a DOM context to look up the DOM tree within: | $(selector).closest(filter,context) |
Parameter | Description |
---|---|
filter | It is a required parameter and is used to specifies a selector expression, element or jQuery object to narrow down the ancestor search |
context | It is an Optional parameter and is used to a DOM element within which a matching element may be found |
<html>
<head>
<style>
.ancestors * {
display: block;
border: 2px solid dodgerblue;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").closest("ul").css({"color": "#000", "border": "2px solid #df65f7"});
});
</script>
</head>
<body>
<div class="ancestors">
<div style="width:500px;">div (great-grandparent)
<ul>ul (second ancestor - second grandparent)
<ul>ul (first ancestor - first grandparent)
<li>li (direct parent)
<span>span</span>
</li>
</ul>
</ul>
</div>
</div>
</body>
</html>