Check if an element is a descendant of another

True when child is inside parent, at any depth.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

check-if-an-element-is-a-descendant-of-another.js
function isDescendant(child, parent) { return child !== parent && parent.contains(child); }

Usage

Markup

fixture.html
<ul id="list"><li id="item">Item</li></ul>

Script

usage.js
const list = document.querySelector('#list');
isDescendant(document.querySelector('#item'), list); // → true
isDescendant(list, list); // → false
list.contains(list); // → true

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

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.

Usage lines executed in headless Chromium against the fixture markup; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.