Node.compareDocumentPosition()

The Node.compareDocumentPosition() method reports the position of its argument node relative to the node on which it is called.

Syntax

node.compareDocumentPosition(otherNode)

Parameters

otherNode

The Node for which position should be reported, relative to node.

Return value

An integer value representing otherNode's position relative to node as a bitmask combining the following constant properties of Node:

Constant Value Description
Node.DOCUMENT_POSITION_DISCONNECTED 1 otherNode and node are in different documents or different trees in the same document
Node.DOCUMENT_POSITION_PRECEDING 2 otherNode precedes node in either a pre-order depth-first traversal of a tree containing both (e.g., as an ancestor or previous sibling or a descendant of a previous sibling or previous sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering
Node.DOCUMENT_POSITION_FOLLOWING 4 otherNode follows node in either a pre-order depth-first traversal of a tree containing both (e.g., as a descendant or following sibling or a descendant of a following sibling or following sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering
Node.DOCUMENT_POSITION_CONTAINS 8 otherNode is an ancestor of node
Node.DOCUMENT_POSITION_CONTAINED_BY 16 otherNode is a descendant of node
Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32 the result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable

More than one bit is set if multiple scenarios apply. For example, if otherNode is located earlier in the document and contains the node on which compareDocumentPosition() was called, then both the DOCUMENT_POSITION_CONTAINS and DOCUMENT_POSITION_PRECEDING bits would be set, producing a value of 10 (0x0A).

Example

const head = document.head;
const body = document.body;

if (head.compareDocumentPosition(body) & Node.DOCUMENT_POSITION_FOLLOWING) {
  console.log('Well-formed document');
} else {
  console.error('<head> is not before <body>');
}

Note: Because the result returned by compareDocumentPosition() is a bitmask, the bitwise AND operator must be used for meaningful results.

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
compareDocumentPosition
1
12
9
9
Only supports contains for elements
≤12.1
4
≤37
18
9
≤12.1
3.2
1.0

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition