从模板导入时节点不带id

时间:2018-01-24 11:22:02

标签: javascript html5 dom

我正在尝试从模板中设置一个节点上的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>

1 个答案:

答案 0 :(得分:2)

node以下是模板的内容,它不是真正的HTML节点,而是DOCUMENT_FRAGMENT_NODE所以它不能拥有id }。

但您可以使用firstElementChild将此ID应用于第一个元素(此处为div):

&#13;
&#13;
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;
&#13;
&#13;