当某些 html 字符串添加到 DocumentFragmentinnerHTML
属性时,不存在子级。但与由createElement
show children 创建的 Element 相同的操作。我创建了一个简单的示例来比较 DocumentFragment 和简单元素的 innerHTML 行为:
const fragment = document.createDocumentFragment();
const div = document.createElement('div')
fragment.innerHTML = "<i>Test</i>";
console.log('fragment children:', fragment.children); // empty
fragment.innerHTML = "<i><b>Test</b></i>";
console.log('fragment children:', fragment.children); // empty
div.innerHTML = "<i>Test</i>";
console.log('div children:', div.children) // has children
div.innerHTML = "<i><b>Test</b></i>";
console.log('div children:', div.children) // has children
但是片段可以显示由 appendChild 添加的孩子:
const span = document.createElement('span');
const fragment2 = document.createDocumentFragment();
fragment2.appendChild(span);
console.log('fragment children for appendChild', fragment2.children);
如何解决这种奇怪的 DocumentFragment 行为?
附加:我需要 DocumentFragment 作为临时 HTML 容器。
JSFiddle与重现问题。