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:

ValueMeaning
1The nodes do not belong to the same document
2The first node is positioned after the second
4The first node is positioned before the second
8The first node is positioned inside the second
16The second node is positioned inside the first
32The 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
NumberWhere two nodes are positioned compared to each other.
ValueMeaning
1The nodes do not belong to the same document
2The first node is positioned after the second
4The first node is positioned before the second
8The first node is positioned inside the second
16The second node is positioned inside the first
32The 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.