javascript - Why is DocumentFragment cleared after appending - Stack Overflow

The first log returns a full li element while the second one returns an empty DocumentFragment. Why? I

The first log returns a full li element while the second one returns an empty DocumentFragment. Why? I couldn't find any information about that behavior in any documentation.

var main = document.getElementById('main');
var fooTemplate = document.getElementById('my-template');
var foo = fooTemplate.content.cloneNode(true);

console.log(foo);
main.appendChild(foo);
console.log(foo);
<template id="my-template">
    <li>foo</li>
</template>

<ul id="main">
</ul>

The first log returns a full li element while the second one returns an empty DocumentFragment. Why? I couldn't find any information about that behavior in any documentation.

var main = document.getElementById('main');
var fooTemplate = document.getElementById('my-template');
var foo = fooTemplate.content.cloneNode(true);

console.log(foo);
main.appendChild(foo);
console.log(foo);
<template id="my-template">
    <li>foo</li>
</template>

<ul id="main">
</ul>

Share Improve this question edited Nov 21, 2021 at 12:02 Michael Haddad 4,4658 gold badges48 silver badges90 bronze badges asked Mar 30, 2015 at 17:57 LithyLithy 87712 silver badges24 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

From the MDN docs on DocumentFragment

Various other methods can take a document fragment as an argument (e.g., any Node interface methods such as Node.appendChild and Node.insertBefore), in which case the children of the fragment are appended or inserted, not the fragment itself.

foo = fooTemplate.content.cloneNode(true) copies the document fragment to foo.

main.appendChild(foo) moves the contents of the foo document fragment into main. foo remains a document fragment, and all the nodes have moved so it's empty.

If you want to keep a reference to the DOM nodes after appending them, you need to store the childNodes, but if you just reference the nodeList, it'll be empty, so you'll need to convert it to an Array:

var nodes = Array.prototype.slice.call(foo.childNodes);
console.log(nodes);
main.appendChild(foo);
console.log(nodes);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745320730a4622431.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信