Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse the DOM until a class is reached?

Tags:

javascript

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
like image 908
cusejuice Avatar asked Sep 03 '25 04:09

cusejuice


1 Answers

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>
like image 98
leonheess Avatar answered Sep 05 '25 01:09

leonheess