在appendchild参数中创建的节点未执行

时间:2014-03-28 01:57:58

标签: javascript

我在Console

中执行以下行
thead=document.createElement('thead')
thead.appendChild((document.createElement('th')).appendChild(document.createTextNode('Inner Text')))

但是当我执行thead时,返回的是一个'thead'标签,其中包含'Inner Text'作为其内容。根据命令执行没有'th'标记。

为什么不起作用?

2 个答案:

答案 0 :(得分:3)

.appendChild()返回附加的子项:

var thead=document.createElement('thead');
var th = document.createElement('th');
th.appendChild(document.createTextNode('Inner Text'));
thead.appendChild(th);

如果您想在一行中执行此操作,可以调用添加的节点的.parentNode

thead.appendChild(document.createElement('th').appendChild(document.createTextNode('Inner Text')).parentNode)

答案 1 :(得分:1)

node.appendChild() 返回附加元素。

  

appendChild方法返回对添加节点的引用。

Source

你想要打破这样的......

var thead = document.createElement('thead');
var th = document.createElement('th');
thead.appendChild(th);
th.appendChild(document.createTextNode('Inner Text')));