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
1 Answer
Reset to default 6From the MDN docs on DocumentFragment
Various other methods can take a document fragment as an argument (e.g., any
Node
interface methods such asNode.appendChild
andNode.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条)