Get Ancestor Elements with JavaScript closest | Plantpot

Get Ancestor Elements with JavaScript closest

Web Dev
Sponsored links

In this article, I will introduce how to get ancestor elements with JavaScript closest.

What is closest()?

The closest() is a method to get the nearest ancestor elements (or itself) of the specified element.

The syntax is as follows.


In the argument "selector", specify id name, class name, tag name, etc.

Sponsored links

Get the ancestor elements with closest()

Below is a sample to get the ancestor elements with closest().


<div id="grandprent">
  <div id="prent">
    <div id="child"></div>


var child = document.getElementById("child");

//<div id="grandprent">
//  <div id="prent">
//    <div id="child"></div>
//  </div>