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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With