AI Workshop: learn to build apps with AI →
DOM Recipes: Check if element is descendant

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


I needed to find out if 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 left; in that case el.parentNode returns null and the while loop ends.

It’s a way to go “up” the element tree until there are no more parents.

Lessons in this unit:

0: Introduction
1: Hiding and showing elements
2: ▶︎ Check if element is descendant
3: Change colors/styles dynamically
4: DOM timing and when elements are ready
5: stopPropagation vs preventDefault
6: How to detect adblockers
7: Creating exit intent popups