附加同一文本节点的子节点不起作用


我找到了答案。使用JavaScript 插入HTML元素两次(或两次以上(

但我需要深入了解这一点。如果没有循环或克隆,这是怎么发生的?

let strong = document.createElement('strong');
let text = document.createTextNode('text');
strong.appendChild(text);
let p = document.querySelector('p')
p.appendChild(strong);
// let anotherText = document.createTextNode('anotherText');
// document.querySelector('strong').appendChild(anotherText)
document.querySelector('strong').appendChild(text);

如果取消对行的注释,则anotherText将被添加到强标记中。为什么最后一个不起作用?

有什么参考资料吗?

let strong = document.createElement('strong');
let text = document.createTextNode('text');
strong.appendChild(text);
let p = document.querySelector('p')
p.appendChild(strong);
// let anotherText = document.createTextNode('anotherText');
// document.querySelector('strong').appendChild(anotherText)
document.querySelector('strong').appendChild(text);
<p></p>

即使我取消注释注释行,它也不起作用。所以sotrong还没有插入到文档中,通过querySelector搜索它会得到undefined。所以,首先需要将它插入到dom中,然后您的文档.querySelector('strong'(就可以工作了。

只需要更多的澄清。但最后一行无法工作,因为文本节点已添加到strong中。

strong = document.createElement('strong');
let text = document.createTextNode('text');
strong.appendChild(text); //You already did the same here 
let p = document.querySelector('p')
p.appendChild(strong);
// let anotherText = document.createTextNode('anotherText');
// document.querySelector('strong').appendChild(anotherText)
document.querySelector('strong').appendChild(text); //This is already executed at strong.appendC... 

最新更新