Aaron Chen Aaron Chen - 1 month ago 9
Javascript Question

Cannot read property childNodes of null

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>

Answer

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>
Comments