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
Try it »
Definition and Usage
compareDocumentPosition() The method compares the document position of the current node with the specified node according to document order.
View the example above; the return value may be:
1: The two nodes have no relationship and do not belong to the same document.
2: The first node (P1) is 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: The nodes have no relationship, or they are two attributes of the same element.
Note: The return value can be a combination of values. For example, returning 20 means 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 IE versions do not support this method.
Syntax
node
.compareDocumentPosition(
node
)
Parameters
| Parameters | Type | Description |
|---|---|---|
| node | Node object | Required. The specified node you want to compare. |
Return Value
| Type | Description |
|---|---|
| Number | Compare the document position of the current node with the specified node
Possible return values: View the example above; the return value may be: 1: The two nodes have no relationship and do not belong to the same document. 2: The first node (P1) is 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: The nodes have no relationship, or they are two attributes of the same element. |
Technical Details
| DOM version | Core Level 1 Node Object |
|---|
Element object