I have the following html code:
<!DOCTYPE html>
<html>
<head>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
</body>
</html>
Yet in the console, I'm receiving an error when it reaches line 9 when it says "type of null does not exist", but clearly the id of the div must exist because I had it declared as an id in the body. How is this possible?
I have the following html code:
<!DOCTYPE html>
<html>
<head>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
</body>
</html>
Yet in the console, I'm receiving an error when it reaches line 9 when it says "type of null does not exist", but clearly the id of the div must exist because I had it declared as an id in the body. How is this possible?
Share Improve this question asked Aug 2, 2015 at 0:00 Adam FreymillerAdam Freymiller 1,9398 gold badges28 silver badges52 bronze badges 1-
1
You never initialize
array_inc
, maybe you meant to writearray
? – Johan Karlsson Commented Aug 2, 2015 at 0:04
3 Answers
Reset to default 3Your html elements aren't loaded when the script is loaded and so don't exist at the time the javascript is executed. Changing the order of your code will solve the problem:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id = "one">1</div>
<div id = "two">2</div>
<div id = "three">3</div>
<div id = "four">4</div>
<script>
var array = ["one", "two", "three", "four"];
for(i = 0; i<array.length; i++){
alert(array[i]);
var tmp = document.getElementById(array[i]);
alert(tmp.id);
alert(tmp.innerHTML);
var to_append = tmp.innerHTML;
array_inc.push(to_append);
alert(array_inc);
console.log(array_inc);
}
</script>
</body>
</html>
Your JS code is probably running before your HTML has fully rendered. To avoid this, don't run your code until the 'DOMContentLoaded' event has fired.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
// your code here
});
</script>
Please load javascript after the whole html body won't get any error