Reputation: 8734
When i am trying to write the code like document.getElementById('id1') after teh script tag it is showing document.getElementById(..) null or not an object.. Is it necessary to write document.getElementById('id1') in function only. If i write this code in function then it is accepting. So what the mistake here.. and if i want to execute a function on loading of the page where to write onLoad() function.. i try to write at but it is not loading.. please help me Thank you
Upvotes: 0
Views: 2151
Reputation: 643
Put your script bellow the element you are getting will also work.
<div id="ele"></div>
<script language="javascript">
alert(document.getElementById('ele').tagName);
</script>
<div id="ele1"></div>
But unless you have special purpose, it's a good habit to write handlers in after document loaded, that is, put your code in window.onload event handler.
Upvotes: 0
Reputation: 24872
In order to be sure that your dom element is loaded, you have to wait the document is loaded.
To do this you can do:
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
</script>
</head>
<body onload="foo()">...</body>
or
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
window.onload = foo;
</script>
</head>
<body>...</body>
Upvotes: 2
Reputation: 15172
If you want the script to run after the page is loaded, you can use window.onload.
<script>
window.onload = function () {
//code goes here
}
.
.
.
</script>
Upvotes: 2