compareDocumentPosition Encodes Relations
Node.compareDocumentPosition returns a bitmask combining containment and document order, so one call answers contains, contained-by, before, and after.
Code
const FLAGS = [
[Node.DOCUMENT_POSITION_DISCONNECTED, 'disconnected'],
[Node.DOCUMENT_POSITION_PRECEDING, 'preceding'],
[Node.DOCUMENT_POSITION_FOLLOWING, 'following'],
[Node.DOCUMENT_POSITION_CONTAINS, 'contains'],
[Node.DOCUMENT_POSITION_CONTAINED_BY, 'contained-by'],
];
function describe(node, other) {
const mask = node.compareDocumentPosition(other);
const names = FLAGS.filter(([bit]) => (mask & bit) !== 0).map(([, name]) => name);
return names.length > 0 ? names.join('+') : 'same node';
}
// 调用方向很重要:A.compareDocumentPosition(B) 描述 B 相对 A 的位置
const list = document.createElement('ul');
const item = document.createElement('li');
list.append(item);
const other = document.createElement('div');
console.log('list vs item :', describe(list, item));
console.log('item vs list :', describe(item, list));
console.log('sibling order:', describe(item, other));
console.log('same node :', describe(item, item));Reading between the statements
compareDocumentPosition Encodes Relations comes down to the function describe.
What to watch for
- Runs on the standard library alone; nothing to install.
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Using it
Signature: function describe(node, other)
Printed lines come labeled — list vs item :, item vs list :, sibling order: — when the file runs.
Key statements
const names = FLAGS.filter(([bit]) => (mask & bit) !== 0).map(([, name]) => name);
return names.length > 0 ? names.join('+') : 'same node';
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 compareDocumentPosition Encodes Relations 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.