innerHTML是否在DOM树中创建节点? [英] Do innerHTML create nodes in the DOM tree?

查看:151
本文介绍了innerHTML是否在DOM树中创建节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

document.getElementById("myDiv").innerHTML = "some_html_code";

将在我的DOM三个中创建节点,因为如果我使用 appendChild ()

will that create nodes in my DOM three as it would if I used appendChild()?

询问的原因是我正在创建一个内存使用率低的移动应用程序。我不想创建很多节点。

Reason for asking is that I'm creating a mobile application where memory usage must be low. I don't want to create a lot of nodes.

推荐答案

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> ;这个大概是:

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.

这篇关于innerHTML是否在DOM树中创建节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆