javascript - 为什么 appendChild() 覆盖 createElement() 如果它被链接在它的末尾?

标签 javascript chaining appendchild createelement

问题: 我试图理解为什么我不能像这样将 appendChild() 方法链接到 document.createElement():

var listItem = document.createElement('li').appendChild(text);

HTML

<ul>
    <li id="one"><em>fresh</em> figs</li>
    <li id="two">pine nuts</li>
    <li id="three">honey</li>
    <li id="four">balsamic vinegar</li>
</ul>

我知道这是正确的做法:

var ul = document.getElementsByTagName('ul')[0];
var txt = document.createTextNode('this is a text string');
var el = document.createElement('li');
el.appendChild(txt);

但为什么当我这样做时:

var ul = document.getElementsByTagName('ul')[0]; 
var text = document.createTextNode('I am the first generated list'); 
var listItem = document.createElement('li').appendChild(text); 
ul.appendChild(listItem);

它删除了我形成的 li 元素,并将文本仅添加到 ul 项目! 为什么?

最佳答案

因为 appendChild 不是为那样工作而设计的。本来可以的,但事实并非如此。要以这种方式工作,appendChild 必须返回对调用它的元素的引用,但它没有;它返回您传递给它的参数。

it deletes the li element I formed

不,它不会删除它;它从不附加它,因为 listItem 不是对您创建的元素的引用;它是文本节点。来自DOM3 spec :

appendChild (modified in DOM Level 3)

Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.

Parameters

  • newChild of type Node
    The node to add. If it is a DocumentFragment object, the entire contents of the document fragment are moved into the child list of this node

Return Value

  • Node
    The node added.

记下返回值。

关于javascript - 为什么 appendChild() 覆盖 createElement() 如果它被链接在它的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977192/

相关文章:

javascript - Node.js 中的包和模块有什么区别

for 循环中来自 LocalForage 的 JavaScript 链式 promise

Python:类似 jQuery 的函数链接?

javascript - 加载时追加子项

c# - 向 XMl 添加节点

JavaScript:获取MySQL时间戳和当前日期之间的天数差异?

javascript - ImmutableJS - 只更新对象中的一个键值

css - appendChild 可能在 IE9 中保持 hover css 状态

javascript - Grunt - grunt-eslint 不启动任务

ruby-on-rails - Ruby on Rails 分段构建查询