3

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>
Donggi Kim
  • 172
  • 2
  • 10
  • 3
    [**Don't use `innerHTML`**](https://stackoverflow.com/questions/595808/is-it-possible-to-append-to-innerhtml-without-destroying-descendants-onclick-function-handler) which swaps out the complete DOM and replaces it with new nodes constructed from the string. It'll also delete your event handlers and every other data you stored or referenced in the DOM. – Bergi Jul 17 '17 at 07:06

2 Answers2

5

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.

Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41
0

When you append the paragraph this way

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

You create another element instance than p so when you try to remove it this way :

body.removeChild(p);

You try to remove something that is not present in your document yet.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35