Why do I get the error cannot read property childNodes of null? This code is obtained from the book SAMS Teach Yourself Javascript in 24 hours.
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<script>
var text = "";
var pElement = document.getElementById("toDoNotes");
for (var i=0; i < pElement.childNodes.length; i++) {
if (pElement.childNodes[i].nodeType ==3){
text += pElement.childNodes[i].nodeValue;
};
}
alert("The paragraph says:\n\n" + text);
</script>
</head>
<body>
<h1>Things To Do</h1>
<ol id="toDoList">
<li>Mow the lawn</li>
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
</body>
</html>
Child nodes include elements, text and comments. Note: The NodeList being live means that its content is changed each time new children are added or removed. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties.
childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.
Your code needs to be executed after the page is completely loaded. You can use the onload event to do this.
Your script is added to the head
element, and this will get executed before the toDoNotes
element is added to the dom. Thus document.getElementById("toDoNotes")
will return a null value.
<html>
<head>
<title>To-Do List</title>
<script>
function init(){
var text = "";
var pElement = document.getElementById("toDoNotes");
for (var i=0; i < pElement.childNodes.length; i++) {
if (pElement.childNodes[i].nodeType ==3){
text += pElement.childNodes[i].nodeValue;
};
}
alert("The paragraph says:\n\n" + text);
}
</script>
</head>
<body onload="init()">
<h1>Things To Do</h1>
<ol id="toDoList">
<li>Mow the lawn</li>
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
</body>
</html>
The JavaScript function is executed before DOM are created. Include the script tag at the end before body tag ended.
YOUR CODE:
<head>
<script></script>
</head>
<body>
</body>
CORRECT WAY:
<head>
// Not here
</head>
<body>
<!-- right before <body> tag is closed -->
<script></script>
</body>
Because, when your JS is executed, your DOM objects are not created yet. So put your script after the body.
</body>
<script>
//---your JS code---
</script>
</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