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

回眸只為那壹抹淺笑 提交于 2021-01-28 12:16:00

问题


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?


回答1:


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.




回答2:


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.




回答3:


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



回答4:


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>


来源:https://stackoverflow.com/questions/18329507/why-is-javascript-invalidating-dom-references-after-i-manipulate-the-bodys-inne

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!