Javascript DOM HTML Node compareDocumentPosition Method

Introduction

Find out where one paragraph is positioned compared to another paragraph:

Click the button to compare the position of the two paragraphs.

View in separate window

<!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>
<p id="demo"></p>

<script>
function myFunction() {/*from w  w w  .  j ava  2  s. co  m*/
  var p1 = document.getElementById("p1").lastChild;
  var p2 = document.getElementById("p2").lastChild;
  var x = p1.compareDocumentPosition(p2);
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

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

The possible return values:

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

The return value could be a combination of values.

The return value 20 means that p2 is inside p1 (16) and p1 is positioned before p2 (4).

compareDocumentPosition(node);

Parameter Values

Parameter TypeDescription
node Node object Required. Specifies the node to compare with the current node



PreviousNext

Related