[英]How to append DOM Element into an empty element in JavaScript?
I have bunch of objects that return a DOM-tree that I then use to append to an element. 我有一堆对象,它们返回一个DOM树,然后将其附加到元素上。 For example,
例如,
var elem = document.createElement('div');
elem.appendChild(callSomePrototypesMethod());
elem.appendChild(callSomePrototypesMethod());
elem.appendChild(callSomePrototypesMethod());
and I will eventually end up in something like: 我最终会遇到类似:
<div>
<div id="...">...</div>
<div id="...">...</div>
<div id="...">...</div>
</div>
Those three DIVs were created by third party code, and I am wrapping them around my DIV tag here, but what I want instead is to just append them to an empty element, but it doesn't work: 这三个DIV是由第三方代码创建的,我将它们包装在我的DIV标签周围,但是我想要的只是将它们附加到一个空元素上,但这是行不通的:
var elem = document.createElement('');
elem.appendChild(callSomePrototypesMethod());
elem.appendChild(callSomePrototypesMethod());
elem.appendChild(callSomePrototypesMethod());
Expected results: 预期成绩:
<div id="...">...</div>
<div id="...">...</div>
<div id="...">...</div>
I'm not sure if this makes any sense to you, but I need to use DOM, and I can't put those content within any other elements... 我不确定这对您是否有意义,但是我需要使用DOM,并且不能将这些内容放在任何其他元素中...
That's what document fragments are for. 这就是文档片段的用途。 You can create a new fragment via
document.createDocumentFragment()
and use it as if it were a single element. 您可以通过
document.createDocumentFragment()
创建一个新片段,并将其当作单个元素使用。
If you want insert the specifieds elements directly in the body of document (not inside an other element like a 'div'), try 如果要直接将指定元素插入文档正文中(而不是插入其他元素(例如“ div”)中),请尝试
document.body.appendChild( callSomePrototypesMethod() );
There is a note about 'document.body.appendChild' in IE. IE中有关于“ document.body.appendChild”的注释。 See http://danielsaidi.wordpress.com/tag/documentbodyappendchild/ .
参见http://danielsaidi.wordpress.com/tag/documentbodyappendchild/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.