.closest()
method provided by jQuery.<!-- html -->Here we want to get the value from the data-id attribute of the parent div (containing class
<div class="topElem" data-id="1" >
<div>First child elem of first div</div>
<img class="imgElem" src="pic.png">/>
</div>
<div class="topElem" data-id="2" >
<div">First child elem of second div</div>
<img class="imgElem" src="pic.png">/>
</div>
topElem
) when the user clicks on the image.//js
// event listener
$('.imgElem').on('click', function (e) {
$(e.target).closest("div.topElem"); // will give you the parent div with the class 'topElem'
$(e.target).closest("div.topElem").data('id'); //will give you the value of the data-id attribute
});
.closest()
returns only one element matching your selection criteria where as .parents()
returns all the matched elements. Also there is significant difference in the way that both these methods work. .parents()
travels all the way up to the DOM's root element and then filters the collection. .closest()
travels the hierarchy until it finds the matched element and then returns. So if you want to get only one element, then .closest()
is more efficient.Using
.parents()
the above code would be// js
// event listener
$('.imgElem').on('click', function (e) {
$(e.target).parents("div.topElem"); // will give you the parent div with the class 'topElem'
$(e.target).parents("div.topElem").data('id'); //will give you the value of the data-id attribute
});