Node.compareDocumentPosition()

The Node.compareDocumentPosition() method reports the position of the given node relative to another node in any document — not just the given node’s document.

The return value is a bitmask of the following values:

Name Value
DOCUMENT_POSITION_DISCONNECTED 1
DOCUMENT_POSITION_PRECEDING 2
DOCUMENT_POSITION_FOLLOWING 4
DOCUMENT_POSITION_CONTAINS 8
DOCUMENT_POSITION_CONTAINED_BY 16
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32

Syntax

compareMask = node.compareDocumentPosition(otherNode)

Parameters

otherNode
The other Node with which to compare the first node’s document position.

Return value

An integer value whose bits represent the otherNode's relationship to the calling node.

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

Specification Status Comment
DOM
The definition of 'Node.compareDocumentPosition()' in that specification.
Living Standard
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Node.compareDocumentPosition()' in that specification.
Obsolete Initial definition

Browser compatibility

DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
compareDocumentPositionChrome Full support YesEdge Full support 12Firefox Full support 9IE Full support 9
Notes
Full support 9
Notes
Notes Only supports contains for elements
Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 9Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support
Full support
See implementation notes.
See implementation notes.

See also