Reputation: 41
i have this code:
<ul id="ul"></ul>
<script>
var playlist = document.getElementById('ul');
var li = document.createElement('li');
li.innerHTML = 'innerHTML';
playlist.appendChild(li);
console.log(playlist.children[0] === li); // true
playlist.innerHTML += 'some text';
console.log(playlist.children[0] === li); // false
console.log(playlist.children[0]); // <li>innerHTML</li>
console.log(li); // <li>innerHTML</li>
</script>
Weird thing is, while first comparation returns true
, after adding 'some text', it isn't equal anymore. Why is that? Is it a bug, or intended behaviour? Is there a way to make the second test return true
too?
Upvotes: 0
Views: 47
Reputation: 144689
That's because you are modifying the innerHTML
property. After that browser creates another li
element, and as every object is unique, the generated li
element is not equal to the previous li
element. You can append a textNode
instead of modifying the innerHTML
property:
playlist.appendChild(document.createTextNode('some text'));
Upvotes: 3
Reputation: 1939
The use of innerHTML
makes the browser parse and regenerate the DOM. Newly created objects are not the same object, despite their content may be equivalent.
When you use console.log(li)
or console.log(playlist.children[0])
the browser converts the objects to textual representations that can be displayed, they display the same text but they are not the same object.
There's a trick to make the comparison return true:
console.log(""+playlist.children[0] == ""+li); // always return true
What that does is implicitly convert the objects to strings before comparing them. Then the resulting strings, as you were claiming are equal (but not the original objects they came from).
If you compare at innerHTML
level they are also equal:
console.log(playlist.children[0].innerHTML == li.innerHTML); // always return true
Upvotes: 0