HTML DOM Element compareDocumentPosition()
Example
Where is "p1" compared to "p2":
const p1 = document.getElementById("p1");
const p2 = document.getElementById("p2");
let position = p1.compareDocumentPosition(p2);
Try it Yourself »
Description
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 |
Note
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.
Syntax
node.compareDocumentPosition(node)
Parameters
Parameter | Description |
Node | Required. The node to compare with current node. |
Return Value
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 |
Browser Support
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 |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.