jQuery .closest() Method Examples
If you are wondering how to find the closest element of an existing element in a web page, then the jQuery closest method is the way to go. In this article, I am going to share easy examples that show how to use it.
How to use jQuery closest method
So here’s what the .closest() method will do: For each element in the set, it will get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
Now let’s consider an example. Let’s assume that we have some nested divs. One of the divs has a button in it and when this button is clicked, we want to highlight the closest div by changing its background color. The other button that exists in the div, when clicked upon, will remove the highlighted background from the closest div.
Example: Find the closest div and highlight it when button is clicked and remove this highlight when another button is clicked using the .closest() method
<style type="text/css">
.green {
color: #009900;
}
.blue {
background-color: #DFF2FF;
}
.red {
color: #D70000;
font-weight: bold;
}
.orange {
border: 10px solid #F90;
font-size: 100%;
font-weight:bold;
font-family: Georgia, "Times New Roman", Times, serif;
font-style: italic;
}
#my_div1, #my_div2, #my_div3 {
padding: 15px;
margin: 5px;
}
</style>
<div id="my_div1" class="orange green">This is MY DIV 1
<div id="my_div2" class="orange green red">This is MY DIV 2
<div id="my_div3" class="orange red">This is MY DIV 3
<p>
<input type="submit" name="sbt_find_closest_div" id="sbt_find_closest_div" value="Find Closest div and highlight it with Blue color">
<input type="submit" name="sbt_remove_from_closest_div" id="sbt_remove_from_closest_div" value="Remove Blue Class From Closest Div">
</p>
</div>
</div>
</div>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
//This will add class to the a div that does NOT have any class applied to it already
$('#sbt_find_closest_div').on("click", function(e){
$(this).closest('div').addClass('blue');
e.preventDefault();
});
//This will remove class from closest div
$('#sbt_remove_from_closest_div').on("click", function(e){
$(this).closest('div').removeClass('blue');
e.preventDefault();
});
});
</script>That’s it!
Do you know of any other ways to use jQuery closest method to find closest div or any other element? Feel free to suggest by commenting below.