How to Get the Closest Parent Element By Tag in JavaScript

Published Feb 24, 2022  ∙  Updated May 2, 2022

How can we get the closest parent element by tag selector in JavaScript?

Suppose we have an event listener that calls the following handler() function.

const handler = (e) => {
  // Get closest parent element
}

Find closest parent element

We can easily get the closest parent element by selector using closest().

const handler = (e) => {
  const element = e.target;
  let c = element.closest("div");
}

However, closest() will check the current element as well, so if the current element is also a div, it will return the current element.

Ignore the current element

In order to ignore the current element, we can call closest() on the parent instead of the current.

const handler = (e) => {
  const element = e.target.parentElement;
  let c = element.closest("div");
}

Property ‘parentElement’ does not exist on type ‘EventTarget’

If we’re using TypeScript, we might run into an error where parentElement is not recognized on the HTML element.

Property 'parentElement' does not exist on type 'EventTarget'.

We can fix this simply by casting our DOM element to an HTMLElement.

const handler = (e: Event) => {
  const element = (e.target as HTMLElement).parentElement;
  let c = element.closest("div");
}

This solution is specifically for EventTarget errors. Unfortunately, there are many other common “Property does not exist” errors in TypeScript.