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>