How to check if an element is a descendant of another
New Course Coming Soon:
Get Really Good at Git
I had the need to find out of an element I got via a click event was a descendant of a particular parent element.
I assigned an id
to that parent, and I checked if the clicked element belonged to its child elements using this loop:
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 =
to iterate until there’s no parent node anymore, in that case el.parentNode
returns null
and the while loop ends.
It’s a way to go “up” in the elements tree until it finishes.
Are you intimidated by Git? Can’t figure out merge vs
rebase? Are you afraid of screwing up something any time
you have to do something in Git? Do you rely on ChatGPT
or random people’s answer on StackOverflow to fix your
problems? Your coworkers are tired of explaining Git to
you all the time? Git is something we all need to use,
but few of us really master it. I created this course to
improve your Git (and GitHub) knowledge at a radical
level. A course that helps you feel less frustrated with
Git. Launching Summer 2024. Join the waiting list!
→ Get my
JavaScript Beginner's Handbook
→ Read my
JavaScript Tutorials
on The Valley of Code
→ Read my
TypeScript Tutorial
on The Valley of Code
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X