How to check if an element is a descendant of another element

I need to find out that the element obtained through the click event is a descendant of a specific parent element.

I assigned oneidGo to the parent and use this loop to check whether the clicked element belongs to its child element:

const isDescendant = (el, parentId) => {
  let isChild = false

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

while (el = el.parentNode) { if (el.id == parentId) { isChild = true } }

return isChild }

document.addEventListener(‘click’, event => { const parentId = ‘mycontainer’

if (isDescendant(event.target, parentId)) { //it is a descendant, handle this case here } else { //it’s not a descendant, handle this case here } })

In the while loop, we use the assignment operator=Iterate until there are no more parent nodes, in this caseel.parentNodeReturnnullAnd the while loop ends.

This is a way to "up" in the element tree to completion.

Download mine for freeJavaScript beginner's manual


More js tutorials: