Categories
JavaScript Answers

How to find the closest ancestor element that has a specific class with JavaScript?

Spread the love

To find the closest ancestor element that has a specific class with JavaScript, we use the closest method.

For instance, we write

const closest = document.querySelector("p").closest(".near.ancestor");

to select the p element with querySelector.

And then we get the closest element from it with classes near and ancestor with the closest method.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *