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这样的库来处理这个问题。
在安慰document.getElementById("demo").firstChild
我得到这个。
突出显示的部分显示空文本。这可能是因为它不是第一个p
元素。
相反,你可以使用firstElementChild
function setText() {
document.getElementById("demo").firstElementChild.innerHTML = 'changed!';
}
setTimeout(setText, 1000);
<div id="demo">
<p>first</p>
<p>second</p>
</div>
你总是可以使用children
方法或querySelector
function SetText(){
document.getElementById('demo').children[0].textContent = "changed"
}
要么
function SetText() {
document.querySelector('#demo > *').textContent = "changed"
}
使用“.firstChild”将选择div中的空格(如果有)。在你的情况下有一些。你有两个选择,要么拿我们的空格/换行,要么改用这个函数......
function setText() {
// doesn't change because the firstChild isn't the <p> element...
// try using firstElementChild
document.getElementById("demo").firstElementChild.innerHTML = 'changed!';
}