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 | const isDescendant = (el, parentId) => { |
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 | document.addEventListener('click', event => { |
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