HTML DOM compareDocumentPosition()
Method
Example
Compare the document position of the current field with the specified field:
var p1 = document.getElementById("p1");
var p2 = document.getElementById("p2");
p1.compareDocumentPosition(p2);
Output result:
4
Definition and Usage
The compareDocumentPosition() method compares the document position of the current node with the specified node in document order.
Refer to the above example, the return values could be:
1: No relationship, these two nodes do not belong to the same document.
2: The first node (P1) is located after the second node (P2).
4: The first node (P1) is positioned before the second node (P2).
8: The first node (P1) is inside the second node (P2).
16: The second node (P2) is inside the first node (P1).
32: No relationship, or the two nodes are attributes of the same element.
Note: The return value can be a combination of these values. For example, a return value of 20 means that P2 is inside P1 (16) and P1 is before P2 (4).
Browser Support
All major browsers support the compareDocumentPosition() method.
Note: Internet Explorer 8 and earlier versions do not support this method.
Syntax
Parameters
Parameter | Type | Description |
---|---|---|
node | Node object | Required. The specified node you want to compare. |
Return Value
Type | Description |
---|---|
Number | Compares the document position of the current node with the specified node. Possible return values: Refer to the above example, the return values could be: 1: No relationship, these two nodes do not belong to the same document. 2: The first node (P1) is located after the second node (P2). 4: The first node (P1) is positioned before the second node (P2). 8: The first node (P1) is inside the second node (P2). 16: The second node (P2) is inside the first node (P1). 32: No relationship, or the two nodes are attributes of the same element. |
Technical Details
| DOM Version | Core Level 1 Node Object | | --- | --- |