JQuery Closest :
JQuery Closest is a method, which is used to get the first ancestor of the selected element. Here Ancestor is a parent or grand parent or great grand parent and so on..
Closest in JQuery available in two flavours;
- closest(filter)
- closest(selector,[context])
closest(filter) :
It returns the closest (first) parent of the given element. Here filter is selector expression, it is required.
closest( selector, [context] )
In this method, a DOM element is used to match the elements.
[html]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>closest demo</title>
<style>
li {
margin: 5px;
padding: 5px;
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<ul>
<li><label class="sample">clickme For Closest</label></li>
<li>You can also <b class="sample">Click me For Closest !</b></li>
</ul>
<script>
$(document).ready(function() {
$(".sample").click(function() {
alert("My Closest Element is : " + $(this).closest("li").html());
})
})
</script>
</body>
</html>
[/html]
Happy Learning 🙂