HTML DOM Element compareDocumentPosition() Method

Definition and Usage

compareDocumentPosition() This method compares two nodes and returns an integer describing their position in the document:

Value Meaning
1 The nodes do not belong to the same document.
2 The first node is after the second node.
4 The first node is before the second node.
8 The first node is inside the second node.
16 The second node is inside the first node.
32 The node is an attribute of the same element.

Comment

The return value can also be a combination of values.

The value 20 indicates that the second node is inside the first node (16), and the first node is before the second node (4).

Example

"p1" compared to "p2":

const p1 = document.getElementById("p1");
const p2 = document.getElementById("p2");
let position = p1.compareDocumentPosition(p2);

Try it yourself

Syntax

node.compareDocumentPosition(node)

Parameter

Parameter Description
Node Required. The node to be compared with the current node.

Return value

Type Description
Number The position where two nodes are compared to each other.
Value Meaning
1 The nodes do not belong to the same document.
2 The first node is after the second node.
4 The first node is before the second node.
8 The first node is inside the second node.
16 The second node is inside the first node.
32 The node is an attribute of the same element.

Browser support

element.compareDocumentPosition() It is a feature of DOM Level 1 (1998).

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support