Latest web development tutorials

HTML DOM compareDocumentPosition method

Elements Object Reference Element object

Examples

Compare the current document location field with the specified field:

var p1=document.getElementById("p1");
var p2=document.getElementById("p2");
p1.compareDocumentPosition(p2);

Output:

4

try it"

Definition and Usage

compareDocumentPosition () method in document order, compare the current node and document location specified node.

See the example above, the return value might be:

1: There is no relationship between these two nodes do not belong to the same document.

2: the first point (P1) located after the second node (P2).

4: the first point (P1) positioned at the second node (P2) before.

8: the first point (P1) located in the second node (P2).

16: the second node (P2) located within the first node (P1).

32: There is no relationship, or two nodes in the two attributes of the same element.

Note: The return value can be a combination. That means that in 20 Back P1 P2 and P1 (16) positioned at P2 (4) above.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support compareDocumentPosition () method

Note: Internet Explorer 8 and earlier versions of IE does not support this method.


grammar

node.compareDocumentPosition(node)

parameter

参数 类型 描述
node Node object 必须。你想比较的指定节点。

return value

类型 描述
Number 比较当前节点与指定节点的文档位置

可能的返回值:

查看以上实例,返回值可能是:

1:没有关系,这两个节点不属于同一个文档。

2: 第一节点(P1)位于第二个节点后(P2)。

4:第一节点(P1)定位在第二节点(P2)前。

8: 第一节点(P1)位于第二节点内(P2)。

16: 第二节点(P2)位于第一节点内(P1)。

32:没有关系的,或是两个节点在同一元素的两个属性。

technical details

DOM version Core Level 1 Node Object


Elements Object Reference Element object