【发布时间】:2022-01-18 08:16:03
【问题描述】:
我有这个 JS 和 HTML 内容:
const parent = document.querySelector('#parent');
const choices = parent.dataset.choices.split(",")
const childTplt = document.querySelector('#children');
for (c of choices) {
let child = childTplt.content.cloneNode(true);
child.appendChild(document.createTextNode(c));
parent.appendChild(child);
}
<ul id="parent" data-choices="one,two,three">
</ul>
<template id="children">
<li> </li>
</template>
并在我的页面上结束:
<ul id="parent" data-choices="one,two,three">
<li> </li>
one
<li> </li>
two
<li> </li>
three</ul>
为什么文本内容最终成为<li> 的兄弟而不是实际的孩子(在<li></li> 内部?
感谢您的意见!
【问题讨论】:
-
对此我不确定,但您可能需要从从模板获得的内容片段中提取
.firstElementChild。我想这会给你<li>节点。 编辑 是的,这行得通。
标签: javascript html dom browser