I have the following very simple code:
<html>
<head>
<script type="text/javascript" >
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
one();
</script>
</head>
</html>
I am getting the following error:Uncaught TypeError: Cannot read property 'appendChild' of null
. Can anybody tell me, where am I going wrong? I am testing in Chrome
.
I have the following very simple code:
<html>
<head>
<script type="text/javascript" >
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
one();
</script>
</head>
</html>
I am getting the following error:Uncaught TypeError: Cannot read property 'appendChild' of null
. Can anybody tell me, where am I going wrong? I am testing in Chrome
.
3 Answers
Reset to default 4document.body.appendChild
is run before the body is defined, hence document.body
is still null
.
Either move this script down under the <body></body>
or delay it's execution with:
window.addEventListener("load", function () { /* we're ready */ });
document.body.appendChild(p)
In this line. Some days ago I had the same problem. This happens if you put your script before of the tag body.
<html>
<head>
<script type="text/javascript" >
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
one();
</script>
</head>
</html>
Will not work. If you put your function call after the tag it works.
<html>
<head>
<script>
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
</script>
</head>
<body>
<body>
<script type="text/javascript" >
one();
</script>
</html>
In your context, "body" yet didn't be initialized, so it is null
It looks like you are missing the body tag from your HTML. So document.body is null