Check if a DOM node is inside a container, optionally inclusive
A dropdown menu closes when the user clicks anywhere outside it. Its global click handler needs one question answered: is event.target inside the menu? The click can land on an element, on a text node, or on the menu itself, and the menu may not even be attached to the page yet while it animates in.
Implement isWithin(container, node, inclusive). It returns true when node is a descendant of container, at any depth.
isWithin(container, node, inclusive = false) // => boolean
node is within container when container is found by walking up from node through its parents.isWithin(menu, menu) is false. When inclusive is true, it is true.document, or a DocumentFragment. Text and comment nodes have no children, so nothing is within them.null, undefined, a plain object), return false.Node.prototype.contains or compareDocumentPosition, and do not modify the DOM.<nav id="menu">
<ul>
<li id="item">Settings</li>
</ul>
</nav>
<main id="page"></main>
const menu = document.getElementById('menu');
const item = document.getElementById('item');
const label = item.firstChild; // the "Settings" text node
isWithin(menu, item); // => true
isWithin(menu, label); // => true
isWithin(item, menu); // => false
isWithin(menu, menu); // => false
isWithin(menu, menu, true); // => true
isWithin(document, item); // => true
isWithin(menu, document.getElementById('page')); // => false
isWithin(menu, null); // => false
document.addEventListener('click', (event) => {
if (!isWithin(menu, event.target, true)) closeMenu();
});