Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript ChildNodes Undefined type error?

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>
like image 944
Gianluca Fuoco Avatar asked Apr 10 '18 03:04

Gianluca Fuoco


1 Answers

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>
like image 128
klugjo Avatar answered Oct 18 '22 17:10

klugjo