How do I check if an element is a descendant of another element using vanilla JavaScript?
Rashid D
rashid d profile pic

To check if an element is a descendant of another element using vanilla JavaScript, you can traverse the DOM tree and check if the parent element contains the target element as one of its descendants. Here's an example of how you can do it:

1
2
3
4
5
6
7
8
9
10
11
12
13

function isDescendant(parent, child) {
  let node = child.parentNode;

  while (node !== null) {
    if (node === parent) {
      return true;
    }
    node = node.parentNode;
  }

  return false;
}

In the above code, theisDescendant() function takes two parameters:parent (the parent element) andchild (the element to check if it is a descendant). We start by assigning the parent element's immediate parent to thenode variable. Then, we enter awhile loop that continues until we reach the top of the DOM tree (node becomesnull). Inside the loop, we check if the currentnode is the same as theparent element. If they match, it means thechild element is a descendant, so we returntrue. Otherwise, we update thenode variable to its parent and continue traversing up the DOM tree. If we reach the end of the loop without finding a match, it means thechild element is not a descendant, so we returnfalse. Here's an example of how you can use theisDescendant() function:

1
2
3
4
5
6

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

const isDescendantElement = isDescendant(parentElement, childElement);
console.log(isDescendantElement); // Output: true or false

In this example, we assume you have two elements in your HTML with theid attributes set as'parent' and'child', respectively. We usedocument.getElementById() to retrieve the elements, and then we pass them to theisDescendant() function. The function will returntrue if thechild element is a descendant of theparent element, andfalse otherwise. By using the providedisDescendant() function, you can easily determine if an element is a descendant of another element using vanilla JavaScript.