The following code example shows Comparing Document Position in JavaScript.
Programmingempire
Example Code to Demonstrate Comparing Document Position in JavaScript
In order to find the relative position of HTML elements, we use the compareDocumentPosition() function. The following example shows there are several HTML elements. When user clicks on the button, it displays the relative positions of the elements.
<html>
<head>
<title>Comparing Document Position</title>
<script>
function f1()
{
var v1=document.getElementById("h");
var v2=document.getElementById("d1");
var v3=document.getElementById("d2");
var v4=document.getElementById("d3");
var v5=document.getElementById("b1");
str="";
str+="Heading and Outer Div: "+v1.compareDocumentPosition(v2)+"<br/>";
str+="Outer Div and Heading: "+v2.compareDocumentPosition(v1)+"<br/>";
str+="Outer Div and Inner Div: "+v2.compareDocumentPosition(v3)+"<br/>";
str+="Outer Div and Third Div: "+v2.compareDocumentPosition(v4)+"<br/>";
str+="Third Div and Button: "+v4.compareDocumentPosition(v5)+"<br/>";
str1=v4.innerHTML;
str1+="<br/>"+str;
v4.innerHTML=str1;
}
</script>
</head>
<body>
<h1 id="h">Relative Positions of Elements</h1>
<div id="d1" style="margin: 50px; padding: 20px; text-align: center;
font-size: 20px;background-color:#ffddaa;color:#ff3311;"><br/><br/>
Outer Div
<div id="d2" style="background-color: #7788aa; width: 200px;color: yellow;">
Inner Div
</div>
<button id="b1" onclick="f1()">Find Relative Position</button>
<div id="d3">Third Div</div>
</div>
</body>
</html>
Output