[英]Cannot read property childNodes of null
Why do I get the error cannot read property childNodes of null? 为什么我得到的错误无法读取null的属性childNodes? This code is obtained from the book SAMS Teach Yourself Javascript in 24 hours.
此代码可在24小时内从SAMS Teach Yourself Javascript一书中获得。
<!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>
Your code needs to be executed after the page is completely loaded. 您的代码需要在页面完全加载后执行。 You can use the onload event to do this.
您可以使用onload事件来执行此操作。
Your script is added to the head
element, and this will get executed before the toDoNotes
element is added to the dom. 您的脚本将添加到
head
元素中,这将在将toDoNotes
元素添加到dom之前执行。 Thus document.getElementById("toDoNotes")
will return a null value. 因此
document.getElementById("toDoNotes")
将返回一个空值。
<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. JavaScript函数在创建DOM之前执行。 Include the script tag at the end before body tag ended.
在body标记结束之前包含脚本标记。
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. 因为,当执行JS时,您的DOM对象尚未创建。 So put your script after the body.
所以把你的脚本放在身体后面。
</body>
<script>
//---your JS code---
</script>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.