Where is "p1" compared to "p2":
const p1 = document.getElementById("p1");
const p2 = document.getElementById("p2");
let position = p1.compareDocumentPosition(p2);
Try it Yourself »
The compareDocumentPosition()
method compares two nodes, and returns an integer describing where they are positioned in the document:
Value | Meaning |
---|---|
1 | The nodes do not belong to the same document |
2 | The first node is positioned after the second |
4 | The first node is positioned before the second |
8 | The first node is positioned inside the second |
16 | The second node is positioned inside the first |
32 | The nodes are attributes on the same element |
The return value can also be a combination of values.
The value 20 means that second node is inside the first (16) and the first node is positioned before the second.
node.compareDocumentPosition(
node)
Parameter | Description |
Node | Required. The node to compare with current node. |
Type | Description |
Number | Where two nodes are positioned compared to each other. |
Value | Meaning |
---|---|
1 | The nodes do not belong to the same document |
2 | The first node is positioned after the second |
4 | The first node is positioned before the second |
8 | The first node is positioned inside the second |
16 | The second node is positioned inside the first |
32 | The nodes are attributes on the same element |
element.compareDocumentPosition()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!