DEV Community

Matt Pignatore
Matt Pignatore

Posted on

Is this element a descendant of another?

The Problem

Recently I was charged with ironing out the functionality of a custom modal which houses a form. I had to be able to open the modal with a button, and close it one of two ways: click outside of the modal, or submit the form.

The Thought Process

Initially I thought it'd be simple! Just write some conditional logic, checking the class of each element in the form. If the event target doesn't have any of those classes, then the modal can be closed. If the submit button is targeted, close the form. But it wasn't this simple...

Reason being that this project includes third-party framework - Select2 - which was generating a dropdown that was positioned absolutely on the page and was not a descendant of my modal! Now, I could have written some JavaScript to add class selectors to those elements on page load, but this seemed inefficient. That's when I decided I had to traverse the DOM a bit.

The Solution

I ended up writing a single function that took two arguments: the target element and the parent I need to check for. The function returns true is it's a descendant of the parent, false if not.

function isDescendant(el, selector) {
  let isChild = false;
  /* 
  if the target element *is* the parent 
  I'm looking for, return true 
  */
  if (el.id === selector) {
    isChild = true;
    return isChild;
  }
  /* 
  this loop travels upward from the target element
  until it reaches the parent I'm searching for
  and returns true
  */
  while (el = el.parentNode) {
    if (el.id === selector) {
      isChild = true;
      return isChild;
    }
  }
  /*
  if neither of the above cases occur, return false.
  The target element is not a descendant.
  */
  return isChild;
}
Enter fullscreen mode Exit fullscreen mode

And there you have it! This function was incredibly helpful in getting my form modal to function properly. Hopefully it can be a bit of help to you too!

Top comments (0)