Reputation: 3
I get this error: "Uncaught TypeError: Cannot set property 'innerHTML' of null"
. I can't find the fault in my code. I don't use CSS now, nor jQuery.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--<script src="js/banner_test_script.js" language="javascript" type="text/javascript"></script>-->
</head>
<body>
<div id="ban"></div>
<script src="js/banner_test_script.js"></script>
</body>
</html>
And here is my JavaScript code:
window.onload = function what()
{
var myTimery = setInterval(function() {
myTimer();
}, 1000);
var imgn = 0;
function myTimer()
{
if (imgn === 0)
{
var d = "../../download.jpg";
imgn++;
}
else if (imgn === 1)
{
var d = "../../images.jpg";
imgn++;
}
else if (imgn === 2)
{
var d = "../../images1.jpg";
resetImgn();
}
var p = '<img src="' + d + '"></img>';
document.getElementById("ban").innerHTML = "lol";
document.writeln(p);
console.log(document.getElementById('ban') + "1");
console.log(document.getElementById("ban") + "2");
}
;
function resetImgn()
{
imgn = 0;
}
;
/*
function myTimer()
{
for (i = 0; i < 200; i++)
{
document.writeln(i);
}
}
;
*/
};
Upvotes: 0
Views: 2165
Reputation: 1075755
If you use document.write
(or document.writeln
) after the initial parsing of the page (which you do, because you're using it in a timer), that implicitly does a document.open
, which wipes out the existing page entirely (and the replaces it with what you write). So your elements no longer exist when you try to look them up.
It's not clear to me what your document.writeln(p)
is meant to do, but if you remove it, you'll stop wiping out your element, and document.getElementById
should be able to find it.
If your goal is to have the image markup in p
written to the ban
element, then:
document.getElementById("bad").innerHTML = p;
...and removing document.writeln
will do it.
Side note: That setInterval
line can be just: var myTimery = setInterval(myTimer, 1000);
Functions are first-class objects.
Side note 2: You seem to be cycling between imgn
0, 1, 2, then back to 0. You have somewhat complicated logic for doing it. Just FYI, there's a handy trick using the %
operator you can use:
imgn = (imgn + 1) % 3;
Assuming you start with 0, the next will be 1, then 2, then 0, then 1...
Upvotes: 3