Check if an element is a descendant of another
True when child is inside parent, at any depth.
function isDescendant(child, parent) { return child !== parent && parent.contains(child); }
Usage
Markup
<ul id="list"><li id="item">Item</li></ul>
Script
const list = document.querySelector('#list');
isDescendant(document.querySelector('#item'), list); // → true
isDescendant(list, list); // → false
list.contains(list); // → true
Know the limits
- Node.contains returns true for the node itself, as the last line shows, so the original called an element its own descendant.
- contains does not cross shadow roots: an element inside a shadow tree is not a descendant of the host’s ancestors.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Check if an element is a descendant of another from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Excludes the element itself, which Node.contains includes. Executed in Chromium. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/check-if-an-element-is-a-descendant-of-another.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.