且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

innerHTML是否在DOM树中创建节点?

更新时间:2023-11-03 09:16:34

var div = document.getElementById("myDiv");

while( div.firstChild ) {
    div.removeChild( div.firstChild );
}

div.appendChild( document.createTextNode("a_html_string") );

当然,如果通过html_string您的意思是由复杂的html组成的字符串,那么当然节点是从html(元素节点,注释节点,文本节点等)创建的。但是一个简单的文本字符串只是一个文本节点。

Of course, if by "html_string" you mean a string consisting of complex html, then of course nodes are created from the html as appropriate (element nodes, comment nodes, text nodes etc). But a simple string of text is simply a single text node.

所以如果你的html字符串是'< div id =hello&gt ;这个大概是:

So if your html string were '<div id="hello">world</div>', that would roughly be:

var div = document.getElementById("myDiv");

while( div.firstChild ) {
    div.removeChild( div.firstChild );
}

var anotherDiv = document.createElement("div");
anotherDiv.setAttribute("id", "hello");
anotherDiv.appendChild(document.createTextNode("world"));
div.appendChild(anotherDiv);

很可能令人震惊的是,一个简单无辜的 setter,这甚至不包括解析html。

It is probably shocking how much is happening with a simple innocent looking .innerHTML setter, and this is not even including parsing the html.

重要的是要注意,这不是垃圾,所有这些对象都被创建是必要的为确保您只创建必要的节点,请勿在节点之间使用不必要的空格。例如

It's important to note that none of this is garbage, all of those objects created are necessary. To make sure you are only creating necessary nodes, do not use unnecessary whitespace between nodes. For example

<span>hello</span> <span>world</span>

是3个文本节点,但

<span>hello</span><span> world</span>

只有2个文本节点。

很久以前,我创建了一个 facetious jsfiddle ,将所有这些转换为DOM代码。内心的仇敌。

A long while ago I created a facetious jsfiddle that converts html to "DOM code" for all of those .innerHTML haters.