The compareDocumentPosition()
method compares two nodes,
and returns an integer describing where they are positioned in the document.
The possible return values:
compareDocumentPosition |
Yes | 9 | Yes | Yes | Yes |
node.compareDocumentPosition(node)
Parameter | Type | Description |
---|---|---|
node | Node object | Required. Specifies the node to compare |
It returns a Number type value to describe the relation between the two nodes.
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: