How do I check if an element is a descendant of another element in JavaScript?
Richard W
richard w profile pic

In JavaScript, you can check if an element is a descendant of another element by traversing the DOM tree and checking for the presence of the ancestor element. Here's how you can accomplish this: 1. Using thecontains() method: - Thecontains() method is available on DOM elements and can be used to check if a given element is a descendant of another element.

1
2
3
4
5
6

   const ancestorElement = document.getElementById("ancestor");
   const descendantElement = document.getElementById("descendant");

   const isDescendant = ancestorElement.contains(descendantElement);
   

In this example,ancestorElement represents the ancestor element, anddescendantElement represents the element you want to check if it is a descendant. Thecontains() method is called on theancestorElement and passed thedescendantElement. It returnstrue if thedescendantElement is a descendant of theancestorElement, andfalse otherwise. 2. Traversing the DOM tree: - If thecontains() method is not available or not suitable for your use case, you can manually traverse the DOM tree using parent nodes until you reach the root element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

   function isDescendant(ancestorElement, descendantElement) {
     let currentElement = descendantElement.parentNode;

     while (currentElement !== null) {
       if (currentElement === ancestorElement) {
         return true;
       }
       currentElement = currentElement.parentNode;
     }

     return false;
   }

   const ancestorElement = document.getElementById("ancestor");
   const descendantElement = document.getElementById("descendant");

   const isDescendant = isDescendant(ancestorElement, descendantElement);
   

In this example, theisDescendant() function takes theancestorElement anddescendantElement as arguments. It starts from thedescendantElement and iteratively moves up the DOM tree by accessing the parent node usingparentNode. If it encounters theancestorElement, it returnstrue. If it reaches the root element (document), it returnsfalse as it didn't find the ancestor. Choose the method that best suits your requirements and the available browser support. Thecontains() method provides a concise way to check for descendant elements, while manually traversing the DOM tree gives you more control and flexibility.