Document.createElement()与Document.createTextNode()的区别 - Javascript

4

我正在努力弄清楚这两者之间的区别:

// first one
var h1 = document.createElement('h1');
var t = document.createTextNode('hey');
h1.appendChild(t);
document.body.appendChild(h1);

// second one
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));

第一个(Document.createElement())完美运行,但第二个(Document.createTextNode())则不行。


1
因为appendChild返回已添加的节点,所以您正在尝试将文本节点附加到body... - Andrew Li
document.createElement('h1').appendChild(document.createTextNode('hey') 的结果是文本节点... 因此您正在将文本节点附加到 body。 - Jaromanda X
2个回答

3
appendChild的返回值是被添加的子节点。
因此,如果我们将变量添加到:
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));

它会被分解成以下内容:

var text = document.createTextNode('hey');
var h1 = document.createElement('h1');
h1.appendChild(text);
document.body.appendChild(text);

text 添加到 body 中会将其从 h1 中移除。 h1 被丢弃了,因为它没有被添加到任何地方。

现在,假设我从 document.body.appendChild(document.createElement('h1')); 开始,这个 h1 标签没有 id,那么我该如何向这个标签添加一些文本呢? - Roni Koren Kurtberg
你需要在文档中搜索它。使用一个变量。不要试图将多个操作塞入一个语句中。 - Quentin
好的。我试图将它编码成一行,因为我需要在JS中构建整个HTML页面。 :) - Roni Koren Kurtberg
h1.innerText和处理文本节点的方式相同,但更加简单。 - Victor Stoddard

0
我找到了一种方法来做这件事:(只需在末尾添加.parentNode)
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')).parentNode);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接