Monday, May 20, 2024
164
rated 0 times [  165] [ 1]  / answers: 1 / hits: 133909  / 14 Years ago, tue, december 21, 2010, 12:00:00
<html>
<head>
<title>Test javascript</title>

<script type=text/javascript>
var e = document.getElementById(db_info);
e.innerHTML='Found you';
</script>
</head>
<body>
<div id=content>
<div id=tables>

</div>
<div id=db_info>
</div>
</div>
</body>
</html>


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?


More From » getelementbyid

 Answers
21

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 </body>-tag, since everything in front of it is loaded at the time of execution, then.


[#94536] Friday, December 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
minab

Total Points: 701
Total Questions: 104
Total Answers: 91

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;