5

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>
Gianluca Fuoco
  • 193
  • 2
  • 8
  • 2
    Please edit the exact error message into your question. – Ry- Apr 10 '18 at 04:01
  • 1
    The problem is `childNodes` includes the text nodes representing the whitespace between `
    ` and `

    `. Text nodes do not have `style` properties

    – Phil Apr 10 '18 at 04:05

1 Answers1

4

Use children[0] instead of 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>
klugjo
  • 19,422
  • 8
  • 57
  • 75