HTML DOM compareDocumentPosition() Method


The HTML DOM compareDocumentPosition() method is used to compare a given node position to any other node in any document. The return type of this method is of type integer to describe their position in the document. The integer return values are as specified −

1: No relationship, the two nodes do not belong to the same document.
2: The first node (para1) is positioned after the second node (para2).
4: The first node (para1) is positioned before the second node (para2).
8: The first node (para1) is positioned inside the second node (para2).
16: The second node (para2) is positioned inside the first node (para1).
32: No relationship, or the two nodes are two attributes on the same element.

Syntax

Following is the syntax for HTML DOM compareDocumentPosition() method −

node.compareDocumentPosition(node)

Here, the node is of type node object and specifies the node that we want to compare with the current node.

Example

Let us look at an example for the compareDocumentPosition() method −

<!DOCTYPE html>
<html>
<body>
<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>
<p>Click the button to compare the position of the two paragraphs.</p>
<button onclick="docPosition()">POSITION</button>
<p id="Sample"></p>
<script>
   function docPosition() {
      var p1 = document.getElementById("para1").lastChild;
      var p2 = document.getElementById("para2").lastChild;
      var x = p2.compareDocumentPosition(p1);
      document.getElementById("Sample").innerHTML = x;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the POSITION button −

In the above example −

We have first created two

elements with id “para1” and “para2”.

<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>

We have then created a button POSTION that will execute the docPosition() method upon being clicked by the user −

<button onclick="docPosition()">POSITION</button>

The docPosition() method gets both the <p> element using the getElementById() method on document object. It then assigns the lastchild property value of both the paragraphs to variable p1 and p2 respectively.

We then call the compareDocumentPosition() method on p2 with p1 as the parameter. This means that we want to compare the position of p2 with respect to p1. Since here the p2 is positioned after p1, so the return value is 2 −

function docPosition() {
   var p1 = document.getElementById("para1").lastChild;
   var p2 = document.getElementById("para2").lastChild;
   var x = p2.compareDocumentPosition(p1);
   document.getElementById("Sample").innerHTML = x;
}

Updated on: 07-Aug-2019

30 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements