最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript ChildNodes Undefined type error? - Stack Overflow

programmeradmin2浏览0评论

Hello I am new to coding and have a generic question, I looked everywhere and couldn't find a solution. I was following a javascript tutorial and came across this particular line of code. The childnode states that the property 'backgroundColor' is undefined and I am not sure why.

error : "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>

Hello I am new to coding and have a generic question, I looked everywhere and couldn't find a solution. I was following a javascript tutorial and came across this particular line of code. The childnode states that the property 'backgroundColor' is undefined and I am not sure why.

error : "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>
Share Improve this question edited Apr 10, 2018 at 14:01 Gianluca Fuoco asked Apr 10, 2018 at 3:59 Gianluca FuocoGianluca Fuoco 3033 silver badges8 bronze badges 2
  • 2 Please edit the exact error message into your question. – Ry- Commented Apr 10, 2018 at 4:01
  • 1 The problem is childNodes includes the text nodes representing the whitespace between <div id="sampDiv"> and <p>. Text nodes do not have style properties – Phil Commented Apr 10, 2018 at 4:05
Add a ment  | 

1 Answer 1

Reset to default 4

Use children[0] instead of childNodes[0]:

https://developer.mozilla/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>

发布评论

评论列表(0)

  1. 暂无评论