开发者

How to append DOM Element into an empty element in JavaScript?

开发者 https://www.devze.com 2022-12-12 07:21 出处:网络
I have bunch of objects that return a DOM-tree that I then use to append to an element. For example, var elem = document.cr开发者_StackOverflow社区eateElement(\'div\');

I have bunch of objects that return a DOM-tree that I then use to append to an element. For example,

var elem = document.cr开发者_StackOverflow社区eateElement('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:

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...


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.


If you want insert the specifieds elements directly in the body of document (not inside an other element like a 'div'), try

document.body.appendChild( callSomePrototypesMethod() );

There is a note about 'document.body.appendChild' in IE. See http://danielsaidi.wordpress.com/tag/documentbodyappendchild/.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号