为什么我不能在这种情况下访问`element.firstChild`?

问题描述 投票:2回答:4

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>。为什么不?

javascript html dom
4个回答
1
投票

元素内的空格被视为文本,文本被视为节点。

如果您将HTML更改为:

<div id="demo"><p>first</p><p>second</p></div>

有用。试试吧。

或者您可以使用node.firstElementChild来忽略前导文本,或者使用像jQuery这样的库来处理这个问题。


1
投票

在安慰document.getElementById("demo").firstChild我得到这个snapshot on logging 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>

0
投票

你总是可以使用children方法或querySelector

function SetText(){
  document.getElementById('demo').children[0].textContent = "changed"
}

要么

function SetText() {
  document.querySelector('#demo > *').textContent = "changed"
}

0
投票

使用“.firstChild”将选择div中的空格(如果有)。在你的情况下有一些。你有两个选择,要么拿我们的空格/换行,要么改用这个函数......

function setText() {
  // doesn't change because the firstChild isn't the <p> element...
  // try using firstElementChild
  document.getElementById("demo").firstElementChild.innerHTML = 'changed!';
}
© www.soinside.com 2019 - 2024. All rights reserved.