ldoroni ldoroni - 3 months ago 13
Javascript Question

document.getElementById doesn’t work

If I write code 2 without code 1, the code works and it shows me “aaaaa”.

But if I write code 1 and code 2, the code doesn’t work. Instead of showing me “vvvaa”, it doesn’t show me anything (not “aaaaa” and not “vvvaa”).

Why doesn’t it work? (The

document.getElementById
doesn’t send the information to the
<div>
.)

Code 1:

document.getElementById('na').innerHTML = "vvvaa";


Code 2:

document.write("<div id='na'> aaaaa </div>");


Complete Code: (the only thing on the page)

<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
timeago('1376743609');
document.write("<div id='na'> aaaaa </div>");
</script>

Answer

Order matters. You cannot access your element 'na' before having it in the document.

You naturally need to add the element to the document first. If that's done, you can access it by functions like getElementById().

This...

document.write("<div id='na'></div>");
document.getElementById('na').innerHTML = "vvvaa";

... will work.

You may shortcut this to:

document.write("<div id='na'>vvvaa</div>");
Comments