The Node.compareDocumentPosition() method compares the position of the given node against another node in any document.
The return value is a bitmask with 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
Nodewith which to compare document positioning.
Return value
An integer value whose bits represent the otherNode's relationship to the calling Node within the Document. More than one of the bits may be set, if multiple scenarios apply. If otherNode is located earlier in the document and also contains the Node on which compareDocumentPosition() was called, then the DOCUMENT_POSITION_CONTAINS and DOCUMENT_POSITION_PRECEDING bits would be set, resulting in a value of 0x0A or decimal 10.
Example
let 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>');
}
Note: Because the result returned by compareDocumentPosition() is a bitmask, the bitwise AND operator has to be used for meaningful results.
Note that the first statement above uses the NodeList.item() method with a parameter value of 0, which is equivalent to getElementsByTagName('head')[0].
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
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
compareDocumentPosition | Chrome Full support Yes | Edge Full support 12 | Firefox Full support 9 | IE
Full support
9
| Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 9 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
Legend
- Full support
- Full support
- See implementation notes.
- See implementation notes.