ldoroni ldoroni - 1 year ago 71
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

doesn’t send the information to the

Code 1:

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

Code 2:

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

Complete Code: (the only thing on the page)

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");
// setTimeout( function(){ timeago(time); }, 2000 );
document.write("<div id='na'> aaaaa </div>");

Answer Source

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().


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>");