This page is Ready to Use

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

compareDocumentPosition

Summary

Compares the position of two nodes in a document.

Method of dom/Nodedom/Node

Syntax

var positionBitmask = node.compareDocumentPosition(/* see parameter list */);

Parameters

otherNode

Data-type
DOM Node


The node to be compared to the reference node, which is the node executing the method.

Return Value

Returns an object of type NumberNumber

Describes how the position of the node specified by the otherNode parameter relates to the position of the reference node. The return value contains one or more of the following flag values:

Node constant name Return value (Integer) Return value (Hexadecimal) Description
DOCUMENT_POSITION_DISCONNECTED 1 0x01 The nodes are disconnected.
DOCUMENT_POSITION_PRECEDING 2 0x02 The position of the node specified by the otherNode parameter precedes the position of the reference node.
DOCUMENT_POSITION_FOLLOWING 4 0x04 The position of the node specified by the otherNode parameter follows the position of the reference node.
DOCUMENT_POSITION_CONTAINS 8 0x08 The reference node contains the node specified by the otherNode parameter.
DOCUMENT_POSITION_CONTAINED_BY 16 0x10 The node specified by the otherNode parameter contains the reference node.
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32 0x20 The node positions depend on the DOM implementation and cannot be compared.

Examples

This example determines if the web document is incorrectly marked up with the body element before the head element. Note: Web browsers sometimes self correct markup errors. HTML5 is the first specification to give guidelines to browser vendors on how they should correct markup errors.

var head = document.getElementsByTagName('head').item(0);
if (head.compareDocumentPosition(document.body) & Node.DOCUMENT_POSITION_FOLLOWING) {
  console.log("well-formed document");
} else {
  console.log("<head> is not before <body>");
}


Notes

For information about the factors that affect the position of nodes within the DOM, see the related specifications.


Related specifications

DOM Level 3 Core
Recommendation

Attributions