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>
。为什么不呢?
最佳答案
元素内的空格被视为文本,文本被视为节点。
如果将 HTML 更改为:
<div id="demo"><p>first</p><p>second</p></div>
它有效。尝试一下。
或者您可以使用node.firstElementChild来忽略前导文本,或者使用像jQuery这样的库来处理这个问题。
关于javascript - 为什么在这种情况下我无法访问 `element.firstChild`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48001089/