最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is DocumentFragment cleared after appending - Stack Overflow

programmeradmin1浏览0评论

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);
发布评论

评论列表(0)

  1. 暂无评论