<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?
This question is related to
javascript
getelementbyid
Script is called before element exists.
You should try one of the following:
Run the code either in onload event, either just before you close body
tag.
You try to find an element wich is not there at the moment you do it.
How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,
window.onload = doStuff;
function doStuff() {
var e = document.getElementById("db_info");
e.innerHTML='Found you';
}
The other alternative is to keep your <script...</script>
just before the closing </body>
tag.
The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload
of the body-element.
Source: Stackoverflow.com