您好,我是编码的新手,有一个一般性的问题,我四处张望,找不到解决方案。我正在关注一个JavaScript教程,并遇到了这一特定的代码行。子节点指出属性“ backgroundColor”是未定义的,我不确定为什么。

错误:“未捕获的typeerror:无法设置未定义的属性'backgroundColor'”

<!doctype html>
<html>
 <head>
 </head>
 <body>


 <div id = "sampDiv">

  <p> This is a txt field </p>

  <p> This is another txt field </p>

  </div>



  <script>

  var sampDiv = document.getElementById("sampDiv");

  sampDiv.childNodes[0].style.backgroundColor = "red";
</script>


</body>
</html>

最佳答案

使用children[0]代替childNodes[0]

https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children



  var sampDiv = document.getElementById("sampDiv");

  sampDiv.children[0].style.backgroundColor = "red";

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <div id = "sampDiv">
      <p> This is a txt field </p>
      <p> This is another txt field </p>
    </div>
  </body>
</html>

09-26 19:34