简体   繁体   English

一步创建Javascript createElement和appendchild

[英]Javascript createElement and appendchild in one step

i want to create an element and then append this with other elements in one step. 我想创建一个元素,然后将其与其他元素一起添加到一个步骤中。

var header = document.createElement("thead").appendChild(document.createElement("tr"));

Why this Code outputs the only TR and not Thead? 为什么此代码仅输出TR,而不输出Thead?

When i use this code then its correct (thead + tr are there) 当我使用此代码时,其正确的(thead + tr在那)

var header = CH.createElement("thead");
    header.appendChild(CH.createElement("tr"));

Because Node.appendChild() returns the appended child ... 因为Node.appendChild()返回附加的子代 ...

var appendedChild = element.appendChild(child);

.. you can simply reference the child's parentNode like so ( sample fiddle ): ..您可以像这样简单地引用孩子的parentNode示例小提琴 ):

var header = document.createElement("thead")
    .appendChild(document.createElement("tr"))
    .parentNode; // the row's parentNode, i.e.: thead

@antisanity has a good solution. @antisanity有一个很好的解决方案。 Another solution if your variable is pre-declared is to do this... 如果预先声明了变量,则另一个解决方案是执行此操作...

(header = document.createElement('thead'))
      .appendChild(document.createElement('tr'));

This ensures that the assignment to header happens before the .appendChild() . 这样可以确保对header的分配发生在.appendChild()之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM