Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a child node live range?

Tags:

javascript

I made a 'p' node and appended it to the 'body'.
Next I changed the styles of the node and remove it from the 'body'. And it worked.
But when I did same thing after change 'body.innerHTML', it didn't work.

Console said,

Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Why does it happen?

<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>
like image 777
Donggi Kim Avatar asked Feb 23 '26 20:02

Donggi Kim


1 Answers

Your problem is that first you set add the element to the body:

body.appendChild(p);

Then you are clearing the innerHTML of the body:

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

Once you do this the p that you created is no longer a node in the body. The new <p> that you created is not the same as the one created by var p = document.createElement('p');

So now when you call:

body.removeChild(p); // It doesn't work.

The error occurs.

like image 120
Alexander Higgins Avatar answered Feb 25 '26 09:02

Alexander Higgins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!