JavaScript ChildNodes Undefined type error? - Stack Overflow

Hello I am new to coding and have a generic question, I looked everywhere and couldn't find a solu

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745588407a4634684.html

相关推荐

  • JavaScript ChildNodes Undefined type error? - Stack Overflow

    Hello I am new to coding and have a generic question, I looked everywhere and couldn't find a solu

    10小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信