JavaScript - compareDocumentPosition() method

revision:


Category : element

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

1 : the nodes do not belong to the same document.
2 : the first node is positioned after the second.
4 : the first node is positioned before the second.
8 : the first node is positioned inside the second.
16 : the second node is positioned inside the first.
32 : the nodes are attributes on the same element.

The return value can also be a combination of values. E.g. The value 20 means that second node is inside the first (16) and the first node is positioned before the second.

Syntax :

        node.compareDocumentPosition(node) 
    

Parameters:

node : required. The node to compare with current node.

Examples:

        const p1 = document.getElementById("p1");
        const p2 = document.getElementById("p2");
        let position = p1.compareDocumentPosition(p2);
    

Practical examples

example: where is "p1" compared to "p2"?

This is a paragraph

This is another paragraph

The position of the two paragraphs is:

code:
                    <div>
                        <p id="p1">This is a paragraph</p>
                        <p id="p2">This is another paragraph</p>
                        <p>The position of the two paragraphs is:</p>
                        <p id="position-1"></p>
                        <p id="position-2"></p>
                        <p id="position-3"></p>
                        
                    </div>
                    <script>
                        const p1 = document.getElementById("p1").lastChild;
                        const p2 = document.getElementById("p2").lastChild;
                        let position = p1.compareDocumentPosition(p2);
                        document.getElementById("position-1").innerHTML = "return value : " + position;
                        
                    </script>