closest And matches Resolve Delegation Targets
matches tests the element itself against a selector, closest walks up through ancestors from itself, and both return null when nothing matches.
Code
// 事件委托的落点判断:matches 检查元素自身,closest 沿祖先链向上找
const card = document.createElement('div');
card.className = 'card';
card.innerHTML = '<button class="action" data-action="save">Save</button>';
document.body.append(card);
const button = card.querySelector('button');
// matches 只看当前元素自身是否命中选择器
console.log('matches self :', button.matches('.action[data-action]'));
console.log('matches card :', button.matches('.card'));
// closest 先查自己再向上走祖先链:找到命中的最近祖先
console.log('closest card :', button.closest('.card') === card);
console.log('closest button :', button.closest('button') === button);
console.log('closest body :', button.closest('body') === document.body);
// 没有命中任何祖先时返回 null,调用方据此忽略无关点击
console.log('closest sidebar :', button.closest('.sidebar'));
// data-action 读取落在最近命中元素上:委托处理器只需要一次 closest
console.log('action value :', button.closest('.card').querySelector('button').dataset.action);How it works
The demo data lives in module-level bindings: card, button.
What to watch for
- The import surface (if any) is all standard library, all versioned with the language itself.
- Uses
document, so it needs a browser context — it will not run as-is in Node without shims.
Using it
Look for the matches self :, matches card :, closest card : prefixes when the file runs; they tie each line to its step.
Key statements
card.innerHTML = '<button class="action" data-action="save">Save</button>';
const button = card.querySelector('button');
const card = document.createElement('div');
Interactive Tools for This Topic
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does closest And matches Resolve Delegation Targets run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.