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>
      

Run codeHide result


+3


source to share


2 answers


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.

+5


source


When you add a paragraph like this

body.innerHTML += '<p>' + p.innerHTML + '</p>';

      

You are instantiating a different element than p

, so when you try to delete it like this:



body.removeChild(p);

      

You are trying to delete something that is not in your document.

0


source







All Articles