JavaScript ChildNodes未定义类型错误?

时间:2018-04-10 03:59:16

标签: 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>

1 个答案:

答案 0 :(得分:2)

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

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

&#13;
&#13;
  var sampDiv = document.getElementById("sampDiv");

  sampDiv.children[0].style.backgroundColor = "red";
&#13;
<!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>
&#13;
&#13;
&#13;