0

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

1
  • sorry... onLoad() try to write at form tag but it is not working.. Commented Dec 13, 2010 at 7:22

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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>

2 Comments

thank you so much.. then what about document.getElementById('someid')
@Mihir, I don't understand what you want. I recommend using console in FireBug (for Firefox) or Developer tools (for Chrome/Safari), if you are playing with DOM.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.