Is there a live node range for children?
I made a "p" node and added it to the "body".
Then I changed the styles of the node and removed it from the "body". And it worked.
But when I did the same after changing body.innerHTML it didn't work.
The console said
Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': the node to be removed is not a child of this node.
Why is this happening?
<p><button onclick="func1()">Result 1</button></p>
<script>
function func1() {
var body = document.body;
var p = document.createElement('p');
p.id = 'p1';
p.innerHTML = 'Icons made by <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a>';
body.appendChild(p);
p.style.color = '#0055aa';
p.style.backgroundColor = '#ffaa00';
// body.removeChild(p); // It works.
body.innerHTML += '<p>' + p.innerHTML + '</p>';
body.removeChild(p); // It doesn't work.
}
</script>
source to share
Your problem is that first you set the element to the body:
body.appendChild(p);
Then you clear the innerHTML of the body:
body.innerHTML += '<p>' + p.innerHTML + '</p>';
Once you do this, the created one is p
no longer a node in the body. The new <p>
one you created is not the same as the one you createdvar p = document.createElement('p');
So when you call:
body.removeChild(p); // It doesn't work.
An error has occurred.
source to share