Reputation: 18093
After checking this answer on Is there a way to check if two DOM elements are equal? I'm trying to check if two elements are equal in javascript using ===
. Surprisingly, when element A
and B
are the same A === B
returns false
while B.isEqualNode(A)
returns true
.
Here's an example:
html:
<div>
<h1>Test</h1>
</div>
JavaScript:
var inMemoryDiv = document.createElement('div');
var inMemoryH1 = document.createElement('h1');
inMemoryH1.innerHTML = "Test";
inMemoryDiv.appendChild(inMemoryH1);
var h1 = document.getElementsByTagName('h1')[0];
alert(h1 === inMemoryH1); // false
alert(inMemoryH1.isEqualNode(h1)); // true
alert(h1.innerHTML === inMemoryH1.innerHTML); // true
Replicated in a fiddle.
Why is this the case?
Upvotes: 5
Views: 3939
Reputation: 120516
isEqualNode
is defined in DOM Level 3 thus:
This method tests for equality of nodes, not sameness (i.e., whether the two nodes are references to the same object) which can be tested with
Node.isSameNode()
. All nodes that are the same will also be equal, though the reverse may not be true.Two nodes are equal if and only if the following conditions are satisfied:
- The two nodes are of the same type.
- The following string attributes are equal: nodeName, localName, namespaceURI, prefix, nodeValue. This is: they are both null, or they have the same length and are character for character identical.
- The attributes NamedNodeMaps are equal. This is: they are both null, or they have the same length and for each node that exists in one map there is a node that exists in the other map and is equal, although not necessarily at the same index.
- The childNodes NodeLists are equal. This is: they are both null, or they have the same length and contain equal nodes at the same index. Note that normalization can affect equality; to avoid this, nodes should be normalized before being compared.
Upvotes: 8
Reputation: 4628
You create a new element. That is not the very same as the already existing one. They are equal though as they have the same structure and content. It's like two string objects are equal if they contain the same text but not the same if you created them separately.
Here's an even simpler case:
var div1 = document.createElement('div');
var div2 = document.createElement('div');
alert(div1 === div2); // false
alert(div1.isEqualNode(div2)); // true
Upvotes: 4