JavaScript ChildNodes 未定义类型错误?

Gia*_*oco 6 javascript types undefined child-nodes

你好,我是编码新手,有一个通用问题,我到处找,找不到解决方案。我正在关注一个 javascript 教程并遇到了这行特定的代码。childnode 声明属性 'backgroundColor' 未定义,我不知道为什么。

错误:“未捕获的类型错误:无法设置未定义的属性‘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>
Run Code Online (Sandbox Code Playgroud)

klu*_*gjo 5

使用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";
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)