Why is my element null?

2019-08-23 04:21发布

问题:

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>

回答1:

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
}


回答2:

onload = function() {
 // put you code here
}


回答3:

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.