0

If I create and append a DOM element like this:

 const myDiv = document.createElement('div');

 container.appendChild(newDiv);

And then do something different, like this for example:

container.innerHTML += '<div class="myClass">Another New Div</div>';

Why can I then no longer remove the first element with:

myDiv.remove()

Why does myDiv not keep the element reference?

It works if I use remove() before I change the innerHTML but not after.

Here is a snippet:

const myDiv = document.createElement('div');
myDiv.textContent = 'Hello';
document.getElementById('container').append(myDiv);
container.innerHTML += '<div class="myClass">Another New Div</div>';
myDiv.remove(); //will not remove
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<div id="container"></div>

</body>
</html>
user44109
  • 121
  • 6
  • Where do you think `myDiv` is after the `.innerHTML` line? What if instead you did `innerHTML = "some content`? Or even `innerHTML = ""`? – Kaiido Sep 20 '22 at 23:47
  • 2
    innerHTML is like a whiteboard, when you change it you erase the whole thing and rewrite it. So the element you had is now gone. – epascarello Sep 20 '22 at 23:50

0 Answers0