Practical Use Cases for JavaScript’s `closest()` Method

Published on 2020-08-12

Practical Use Cases for JavaScript’s `closest()` Method

Have you ever had the problem of finding the parent of a DOM node in JavaScript, but aren’t sure how many levels you have to traverse up to get to it? Let’s look at this HTML for instance:

<div data-id="123"><button>Click me</button></div>

That’s pretty straightforward, right? Say you want to get the value of data-id after a user clicks the button:

var button = document.querySelector("button");

button.addEventListener("click", (evt) => {
  console.log(evt.target.parentNode.dataset.id);
  // prints "123"
⁠});

In this very case, the Node.parentNode API is sufficient.

Read the entire article on how to use the element.closest selector on CSS-Tricks: