debel
debel

Reputation: 33

Why is JavaScript invalidating DOM references after I manipulate the body's innerHTML?

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

Answers (4)

Hasan Saeed
Hasan Saeed

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

Alnitak
Alnitak

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

Andrey Shatilov
Andrey Shatilov

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

RichieHindle
RichieHindle

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

Related Questions