【发布时间】:2017-12-28 02:58:31
【问题描述】:
function setText() {
// doesn't change... why not!?
document.getElementById("demo").firstChild.innerHTML = 'changed!';
}
//calling the function with setTimeout to make sure the HTML is loaded
setTimeout(setText, 500);
<div id="demo">
<p>first</p>
<p>second</p>
</div>
我似乎无法将<p>first</p> 更改为<p>changed!</p>。为什么不呢?
【问题讨论】:
-
firstChild在这种情况下是一个文本元素,表示<div id="demo">和<p>之间的空格 -
firstElementChild会像魅力一样工作 -
甚至更简单~
document.querySelector('#demo > *').textContent = 'changed' -
请将其记录到控制台并跟踪结果
标签: javascript html dom