Skip to content

How to check if an element is a descendant of another

I had the need to find out of an element I got via a click event was a descendant of a particular parent element.

I assigned an id to that parent, and I checked if the clicked element belonged to its child elements using this loop:

const isDescendant = (el, parentId) => {
  let isChild = false

  if (el.id === parentId) { //is this the element itself?
    isChild = true
  }

  while (el = el.parentNode) {
    if (el.id == parentId) {
      isChild = true
    }
  }
  
  return isChild
}

document.addEventListener('click', event => {
  const parentId = 'mycontainer'

  if (isDescendant(event.target, parentId)) {
    //it is a descendant, handle this case here
  } else {
    //it's not a descendant, handle this case here
  }
})

In the while loop we use the assignment operator = to iterate until there’s no parent node anymore, in that case el.parentNode returns null and the while loop ends.

It’s a way to go “up” in the elements tree until it finishes.


→ Get my JavaScript Beginner's Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list