jQuery closest() Method - CodingTag
×


jQuery closest()

0 700

  • This jQuery method is used to fetch the first ancestor of the selected HTML elements.
  • If we talk about the DOM traversal tree, this method traverses the DOM tree upward from current element to all ancestors up to root element of the webpage and returns the first ancestor.
  • To traverse only the direct parent element of the selected element, use parent() jQuery method.
  • To traverse the all ancestors up to the root element of the selected element, use parents() jQuery method.
  • If you want to traverse the direct child or descendent elements of selected HTML element use either find() or chidren() jQuery methods.

Related Topics:

jQuery parentsUntil
jQuery wrapInner

jQuery closest

Syntax:

This method has two different signatures.

$(selector).closest(filter) ;

Parameter description:

  • filter: This parameter is used to represents to narrow down the ancestor search. It can be an expression, element or jQuery object. It is optional.
  • $(selector).closest(filter,context);
  • filter: This parameter is used to represents to narrow down the ancestor search. It can be an expression, element or jQuery object. It is optional.
  • context: This parameter represents a DOM element within which a matching element may be found. It is also optional.

Example:

In this example we will return the first ancestor of <b> element.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:30px;
margin:10px;
font-size:20px;
}
p{
background:yellow;
padding:25px;
margin:10px;
}
span{
background:lightgray;
padding:20px;
margin:10px;
}
b{
background:blue;
padding:15px;
margin:10px;
color:white;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("b").closest("span").css("border","2px solid red");
});
});
</script>
</head>
<body>

<h2> jQuery closest() Method Example </h2>
<div>
div element(great grand parent)
<p> p element(grand parent)
<span> span element(direct parent)
<b> Hello Friends!! Welcome to CodingTag </b></span></p>
</div>
<button> Click Me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Leave a Reply


Comments
    Waiting for your comments