Categories
JavaScript Answers

How to Find the Closest Element to a Parent Element in an HTML Document without jQuery?

Spread the love

To find the closest parent element to an HTML element in an HTML document without jQuery, we can use the closest method to find the closest parent of the given element.

For instance, if we have the following HTML:

<table>  
  <thead>  
    <tr>  
      <th>head</th>  
    </tr>  
  </thead>  
  <tbody></tbody>  
</table>

Then we can write:

const th = document.querySelector('th')  
console.log(th.closest('thead'));

to get the th element with document.querySelector .

Then we call closest on it with the 'thead' string to get the thead element closest to the th element.

The console log should log the thead element as a result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.