Element compareDocumentPosition Method - Javascript DOM

Javascript examples for DOM:Element compareDocumentPosition

Description

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

The possible return values would specify:

Value Meaning
1No 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).
16 The 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 also be a combination of values.

For example, the returnvalue 20 means that p2 is inside p1 (16) AND p1 is positioned before p2 (4).

Parameter Values

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

Return Value:

A Number, representing where two nodes are positioned compared to each other.

The following code shows how to Find out where one paragraph is positioned compared to another paragraph:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<p id="p1">This is a paragraph</p>
<p id="p2">This is another paragraph</p>

<p>Click the button to compare the position of the two paragraphs.</p>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {// w  w w. j av  a2  s  .c o 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>

Related Tutorials