Javascript Reference - HTML DOM isSameNode Method








The isSameNode() method checks if two nodes are the same node.

Browser Support

isSameNode Yes Yes Yes Yes Yes

Syntax

node.isSameNode(node)

Parameters

Parameter Type Description
node Node object Required. The node to compare




Return Value

It returns a Boolean type.

true if the two nodes are the same node, otherwise false.

Example

The following code shows how to check if two nodes are the same node.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<ul id="myList"><li>A</li><li>B</li></ul>
<!--  ww w.j  a v a 2  s.c om-->
<script>
function myFunction()
{
    var item1=document.getElementById("myList");
    var item2=document.getElementsByTagName("UL")[0];
    var x=document.getElementById("demo");
    x.innerHTML=item1.isSameNode(item2);
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

isSameNode method compares objects that you have obtained from different queries.

<!DOCTYPE HTML> 
<html> 
<body> 
    <table> 
        <tbody id="SurveysBody"> 
            <tr id="myRow"><td>A</td><td>B</td></tr> 
        </tbody> 
    </table> 
    <pre id="results"></pre> 
    <script> 
        var elemByID = document.getElementById("myRow"); 
        var elemByPos = 
          document.getElementById("SurveysBody").getElementsByTagName("tr")[0]; 
        if (elemByID.isSameNode(elemByPos)) { 
            document.getElementById("results").innerHTML = 
                                             "Objects are the same"; 
        } <!--from  w  w  w .java 2  s. com-->
    </script> 
</body> 
</html>

Click to view the demo

Compare two table rows

The following code compares two rows in a table.

<!DOCTYPE HTML> 
<html> 
    <body> 
        <table> 
            <tbody> 
                <tr class="myRow"><td>Plum</td><td>Purple</td></tr> 
            </tbody> 
        </table> 
        <table> 
            <tbody> 
                <tr class="myRow"><td>Plum</td><td>Purple</td></tr> 
            </tbody> 
        </table> 
        <pre id="results"></pre> 
        <script> 
            var elems = document.getElementsByClassName("myRow"); 
            if (elems[0].isEqualNode(elems[1])) { 
                document.getElementById("results").innerHTML = 
                                             "Elements are equal"; 
            } else { <!-- w ww.j  a v  a2  s .co  m-->
                document.getElementById("results").innerHTML = 
                                             "Elements are NOT equal"; 
            } 
        </script> 
    </body> 
</html>

Click to view the demo