JavaScript - isSameNode() method

revision:


Category : element

The isSameNode() method checks if two nodes are the same node. The method returns true if the two nodes are the same node, otherwise false.

Tip: use the isEqualNode() method to check if two nodes are equal, but not necessarily the same node..

Syntax :

        node.isSameNode(node)
    

Parameters:

node : required. The node to compare.

Examples:

        var item1 = document.getElementById("myList1");      // An 

Practical examples

example: compare two nodes with the isSameNode() method
  • Coffee
  • Tea

same node?

code:
                    <div>
                        <button onclick="sameFunction()">Try it</button>
                        <ul id="myList"><li>Coffee</li><li>Tea</li></ul>
                        <p>same node? <span id="same-1" style="color: red"></p>
                    </div>
                    <script>
                        function sameFunction() {
                            var item1 = document.getElementById("myList");
                            var item2 = document.getElementsByTagName("ul")[2];
                            var x = item1.isSameNode(item2);
                            document.getElementById("same-1").innerHTML = x;
                        }
                    </script>
                

example: use the === operator to check if two nodes are the same node.
  • Coffee
  • Tea
code:
                    <div>
                        <button onclick="sameNodeFunction()">Try it</button>
                        <ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
                    </div>
                    <script>
                        function sameNodeFunction() {
                            var item1 = document.getElementById("myList1");
                            var item2 = document.getElementsByTagName("UL")[3];
                            if (item1 === item2) { 
                                alert("THEY ARE THE SAME!!");
                            } else {
                                alert("They are not the same.");
                            }
                        }
                    </script>