我正在尝试从模板中设置一个节点上的id,但是我不能让它工作,div不接受id。
let template = document.getElementById("template-wide-image");
let node = document.importNode(template.content, true);
node.id = "mouhaha";
console.log(node.id); // mouhaha
document.getElementById("article").appendChild(node); // shows on screen as expected
console.log(document.getElementById(node.id)); // null
<div id="article"></div>
<template id="template-wide-image">
<div class="article-wide-image droppable">
<img src="" alt="Drop image here" class="droppable">
</div>
</template>
答案 0 :(得分:2)
node
以下是模板的内容,它不是真正的HTML节点,而是DOCUMENT_FRAGMENT_NODE
所以它不能拥有id
}。
但您可以使用firstElementChild
将此ID应用于第一个元素(此处为div
):
let template = document.getElementById("template-wide-image"),
node = document.importNode(template.content, true),
myId = "mouhaha";
node.firstElementChild.id = myId;
console.log(node.firstElementChild);
document.getElementById("article").appendChild(node); // shows on screen as expected
console.log(document.getElementById(myId));
&#13;
<div id="article"></div>
<template id="template-wide-image">
<div class="article-wide-image droppable">
<img src="" alt="Drop image here" class="droppable">
</div>
</template>
&#13;