Friday, January 4, 2019

getelementbyid - Javascript can't find element by id?






Test javascript















If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?


Answer



The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:



window.onload = function () {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
};


Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.



Another approach is to place the script tag right before your closing -tag, since everything in front of it is loaded at the time of execution, then.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...