Friday 4 January 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...