0

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>
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Brett
  • 19,449
  • 54
  • 157
  • 290
  • 5
    Make sure that you call `document.getElementById` *after* the concerning element has been parsed and inserted into the DOM. – Gumbo Nov 14 '10 at 20:37
  • possible duplicate of [Why does jQuery or a DOM method such as \`getElementById\` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Bergi Apr 25 '13 at 11:46

3 Answers3

2

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
}
Ben
  • 60,438
  • 111
  • 314
  • 488
  • Yeah..... I was calling the javascript in the page, in the body section, but above the elements..... moved it below them & it works! :) – Brett Nov 14 '10 at 20:43
1
onload = function() {
 // put you code here
}
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
0

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.

Aaron
  • 802
  • 7
  • 17
  • Yep.... I fixed it up liked that just before I seen your answer going by the other answers haha :) – Brett Nov 14 '10 at 20:45