Get Ancestor Elements with JavaScript closest

01/08/2022

Contents

In this article, you will learn 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.

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>