Get Ancestor Elements with JavaScript closest

Web Design & Web Development
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.

element.closest(selector);

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().

HTML

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

JavaScript

var child = document.getElementById("child");
console.log(child.closest("#grandprent"));

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