Javascript Reference - HTML DOM compareDocumentPosition Method








The compareDocumentPosition() method compares two nodes, and returns an integer describing where they are positioned in the document.

The possible return values:

  • 1: No relationship, the two nodes are the same document.
  • 2: The first node is positioned after the second node.
  • 4: The first node is positioned before the second node.
  • 8: The first node is positioned inside the second node.
  • 16: The second node is positioned inside the first node.
  • 32: the two nodes are two attributes on the same element.




Browser Support

compareDocumentPosition Yes 9 Yes Yes Yes

Syntax

node.compareDocumentPosition(node)

Parameters

Parameter Type Description
node Node object Required. Specifies the node to compare

Return Value

It returns a Number type value to describe the relation between the two nodes.





Example

The following code shows how to find out where one paragraph is positioned relative to another paragraph.


<!DOCTYPE html>
<html>
<body>
<p id="p1">This is a paragraph</p>
<p id="p2">This is another paragraph</p>
<button onclick="myFunction()">test</button>
<script>
function myFunction()<!-- ww w . j  a v  a  2s  .c o  m-->
{
    var p1=document.getElementById("p1").lastChild;
    var p2=document.getElementById("p2").lastChild;
    console.log(p1.compareDocumentPosition(p2));
}
</script>

</body>
</html>

The code above is rendered as follows: