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.

JavascriptForm Validation

Code

javascriptsnippet
19 lines
// 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

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.