The Node.compareDocumentPosition() method compares the position of the current node against another node in any other 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 |
compareMask = node.compareDocumentPosition(otherNode)
otherNodeNode with which to compare document positioning.An integer value whose bits represent the calling Node's relationship to otherNode 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.
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>");
}
Note: Because the result returned bycompareDocumentPosition is a bitmask, the bitwise and operator has to be used for meaningful results.
Note: First statement uses NodeList method item(0), which is equivalent to getElementsByTagName('head')[0].
| 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 |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | Yes | Yes | 9 | 5
|
Yes | Yes |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Yes | Yes | Yes | 9 | Yes | Yes | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition