Why is my element null?
Why when I do an alert
of the value (see below) 开发者_如何转开发it returns null
? When an element with that ID exists?
// make reference to divs
var countdown_timer = document.getElementById("countdown_timer");
var countdown_image = document.getElementById("countdown_image");
// For element manipulation
if (type == 'image') {
var element = countdown_image;
} else if (type == 'timer') {
var element = countdown_timer;
}
alert(countdown_timer);
The div is as below..
<div class="timer" id="countdown_timer"></div>
It's possible that the javascript is being executed before the elements on your page are not loaded, thus the selector isn't finding anything. Is your javascript above the <body>
tag? Try putting it after </body>
and see how that works for you.
Another solution is to do:
window.onload = function () {
//put all your JS here
}
onload = function() {
// put you code here
}
Your call to document.getElementById
needs to be after the markup for the div.
<div class="timer" id="countdown_timer"></div>
<script type="text/javascript">
var countdown_timer = document.getElementById("countdown_timer");
...
</script>
Alternatively, you could use the window.onload event, which would be the better way to go.
精彩评论