/

How to Check if an Element is a Descendant of Another

How to Check if an Element is a Descendant of Another

When working with events in JavaScript, you may need to determine if a clicked element is a descendant of a specific parent element. In this tutorial, I will show you how to accomplish this task using a loop.

To begin, assign an id to the parent element that you want to check against. For this example, let’s assume the parent element has an id of “mycontainer”.

Next, create a function called isDescendant that takes two parameters: the clicked element (el) and the id of the parent element (parentId). Inside the function, initialize a variable called isChild to false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const isDescendant = (el, parentId) => {
let isChild = false;

if (el.id === parentId) { // Check if this is the element itself
isChild = true;
}

while (el = el.parentNode) {
if (el.id === parentId) { // Check if the element is a child of the parent
isChild = true;
}
}

return isChild;
}

In the isDescendant function, we first check if the id of the clicked element matches the id of the parent element. If they match, we set isChild to true.

Next, we enter a while loop to iterate through the parent nodes of the clicked element. Inside the loop, we check if the id of the current parent node matches the id of the parent element. If they match, we also set isChild to true.

Finally, we return the value of isChild to indicate whether the clicked element is a descendant of the parent element.

To use this function, add an event listener to the document for the “click” event. Inside the event listener, call the isDescendant function, passing in the clicked element and the id of the parent element as arguments. Based on the return value of isDescendant, you can handle the appropriate case.

1
2
3
4
5
6
7
8
9
document.addEventListener('click', event => {
const parentId = 'mycontainer';

if (isDescendant(event.target, parentId)) {
// The clicked element is a descendant, handle this case here
} else {
// The clicked element is not a descendant, handle this case here
}
});

By utilizing the isDescendant function and the event listener, you can easily determine if an element is a descendant of another element and perform specific actions accordingly.

Tags: JavaScript, event handling, DOM manipulation