How do I check if an element is a child of another element in JavaScript?
Alex K
alex k profile pic

To check if an element is a child of another element in JavaScript, you can use thecontains() method or navigate through the element's parent nodes. Here's a step-by-step guide on how to achieve this: 1. Define the parent and child elements:

1
2
3
4

   const parentElement = document.getElementById("parent");
   const childElement = document.getElementById("child");
   

Replace"parent" and"child" with the respective IDs or references to your elements. 2. Using thecontains() method:

1
2
3

   const isChild = parentElement.contains(childElement);
   

Thecontains() method is called on the parent element and checks if the specified element is a descendant (child, grandchild, etc.) of the parent. It returnstrue if the element is a child andfalse otherwise. 3. Navigating through parent nodes:

1
2
3
4
5
6
7
8
9
10
11

   let isChild = false;
   let currentElement = childElement.parentNode;
   while (currentElement !== null) {
     if (currentElement === parentElement) {
       isChild = true;
       break;
     }
     currentElement = currentElement.parentNode;
   }
   

This approach iterates through the parent nodes of the child element and checks if any of the parent nodes match the parent element. It sets theisChild flag totrue if a match is found. Choose the method that best suits your needs and adjust the code as necessary to fit your specific use case. Both approaches are commonly used to check if an element is a child of another element in JavaScript. Note that if you are working with jQuery, you can also use theis() method to check if an element is a child of another element. The syntax would be$(childElement).is(parentElement) to check if the child is a child of the parent.