【问题标题】:Why can't I access `element.firstChild` in this case?在这种情况下,为什么我不能访问 `element.firstChild`?
【发布时间】: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>

我似乎无法将&lt;p&gt;first&lt;/p&gt; 更改为&lt;p&gt;changed!&lt;/p&gt;。为什么不呢?

【问题讨论】:

标签: javascript html dom


【解决方案1】:

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

如果您将 HTML 更改为:

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

它有效。试试看。

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

【讨论】:

  • 啊啊啊!那很有意思。谢谢。
  • 这有点奇怪
  • @Phil 当然,可以优化。但问题不在于寻求优化的解决方案。它是在询问这个概念……而 jeprubio 解释得很好,让我理解!
  • @Grateful 你不需要接受答案。如果提供了副本,您可以对其进行投票或等待社区投票。
【解决方案2】:

安慰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>

【讨论】:

  • nodeType: 3 是真正的说明,而不是内容
【解决方案3】:

您始终可以使用children 方法或querySelector

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

或者

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

【讨论】:

  • 没有必要使用:first-childquerySelector 已经在这样做了
【解决方案4】:

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

function setText() {
  // doesn't change because the firstChild isn't the <p> element...
  // try using firstElementChild
  document.getElementById("demo").firstElementChild.innerHTML = 'changed!';
}

【讨论】:

  • 欢迎来到 Stack Overflow!尽管此代码可能有助于解决问题,但它没有解释为什么和/或如何回答问题。提供这种额外的背景将显着提高其长期教育价值。请编辑您的答案以添加解释,包括适用的限制和假设。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 2016-08-04
相关资源
最近更新 更多