JavaScript ChildNodes 未定义类型错误?

JavaScript ChildNodes Undefined type error?

您好,我是编码新手,有一个一般性问题,我到处都找了,找不到解决方案。我正在学习 javascript 教程并遇到了这行特定的代码。子节点声明 属性 'backgroundColor' 未定义,我不确定为什么。

错误:"Uncaught typeerror: cannot set property 'backgroundColor' of undefined"

<!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>