Skip to main content

Andreas Remdt

Article

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"<buttonClick 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, … Read article “Practical Use Cases for JavaScript’s closest() Method”