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

Spread the love

Sometimes, we want to find the closest ancestor element that has a specific class with JavaScript.

In this article, we’ll look at how to find the closest ancestor element that has a specific class with JavaScript.

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

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.

Then we call closest with the selector of the element that’s closes to the p element we’re looking for.

Conclusion

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

Leave a Reply

Your email address will not be published.