I have HTML like:
<div id="hooray" class="section">
<div>
<div>
<div id="click">click</div>
</div>
</div>
</div>
When I click the div
with class click
, I want to move up the DOM until reaching the nearest section
and grab the id
.
With JQuery, I would use something like $().closest('div.section')
, but how do I do that with pure Javascript without hardcoding in every parentNode
?
var node = document.getElementById('click').parentNode.parentNode....etc
You can just use Element.closest():
let closestElement = document.getElementById('click').closest('.section');
Here is a snippet to show it in action:
console.log(document.getElementById('click').closest('.section').id);
<div id="hooray" class="section">
<div>
<div>
<div id="click">click</div>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With