Node Contains Powers Click-Outside Dismissal
Node.contains answers whether one node sits inside another, inclusive of itself, which is the check a click-outside handler needs before closing a menu.
Code
// Click-outside dismissal: Node.contains answers "is this node inside that one?"
const menu = document.createElement('ul');
menu.innerHTML = '<li>Copy</li><li>Paste</li>';
document.body.append(menu);
const openMenu = () => { menu.hidden = false; };
const closeMenu = () => { menu.hidden = true; };
document.addEventListener('click', (event) => {
// Clicks on the menu itself (or its items) keep it open; anything else closes it
if (!menu.contains(event.target)) closeMenu();
});
openMenu();
console.log('menu open:', !menu.hidden);
// contains() is inclusive: a node contains itself, so re-clicking the trigger never closes instantly
console.log('menu contains itself:', menu.contains(menu));
console.log('item is inside:', menu.contains(menu.querySelector('li')));What the demo dismisses
The document-level click handler closes the menu only when menu.contains(event.target) is false: clicks on the list itself or its li items keep it open, and anything else in the page closes it. Opening first, the printed menu open line is true.
The inclusive semantics get their own checks: menu.contains(menu) is true because a node contains itself, and the first li is inside, so re-clicking a menu item never closes the menu by accident.
Caveats and details
- contains is inclusive, so the trigger element should sit inside the menu.
- event.target can be any descendant; contains handles the whole subtree.
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Why keep the trigger inside the menu check?
- contains counts the node itself, so menu.contains(menu) is true; clicks on the menu area therefore never close it instantly by accident.
Report a problem with this exampleOpens a pre-filled issue on GitHub.