Reputation: 33
I was messing around with some simple JS code and came across the following:
document.body.innerHTML += '<div id="div1">some text</div>';
var my_div = document.getElementById('div1');
document.body.innerHTML += '<div id="div2">some text</div>';
my_div.innerHTML = "some other text"; //doesn't work
It would seem that after manipulating the parent element (the body) the reference to the DOM node is invalidated. What am I doing wrong here?
Upvotes: 2
Views: 528
Reputation: 21
You should use like this, I think it will work fine.
<body>
</body>
<script type="text/javascript">
document.body.innerHTML += '<div id="div1">some text</div>';
var my_div = document.getElementById('div1');
document.body.innerHTML += '<div id="div2">some text</div>';
my_div.innerHTML = "some other text"; //doesn't work
</script>
Upvotes: -1
Reputation: 339836
You are not "manipulating" the innerHTML
, you are overwriting it!
When you use +=
on .innerHTML
the net result is that you end up serialising the entire DOM, appending the new string, and then deserialising the entire resulting HTML string back into DOM nodes. In the process, all existing DOM nodes get destroyed.
IMHO, you should never use .innerHTML
to manipulate DOM nodes, you should only use it to create them.
Upvotes: 2
Reputation: 576
you can use like this:
document.body.innerHTML += '<div id="div1">some text</div>';
var my_div = document.getElementById('div1');
var div2 = document.createElement('div');
div2.id = 'div2';
div2.innerHTML = 'some text';
my_div.parentNode.insertBefore(div2, my_div);
my_div.innerHTML = "some other text"; //work
Upvotes: 0
Reputation: 281505
When you do this:
document.body.innerHTML += '<div id="div2">some text</div>';
it's the same as this:
document.body.innerHTML = document.body.innerHTML + '<div id="div2">some text</div>';
which as you can see replaces the whole of the body, recreating all the elements.
Upvotes: 4