SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    Oct 2007
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    getElementById execution

    Hello,

    Is an event required to run getElementbyId? When I place the following in a page and run it in Firefox or IE getElementById doesn't seem to be executed. If I place getElementById in a function and use onload it does run.

    Code:
    <script type="text/javascript">
    var me = document.getElementById("blah2");
    alert(me.nodeName);
    
    </script>  
      
    <p id="blah2">hello</p>

  2. #2
    SitePoint Guru Ruben K.'s Avatar
    Join Date
    Jun 2005
    Location
    Alkmaar, The Netherlands
    Posts
    693
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    getElementById does indeed require an event

  3. #3
    SitePoint Member
    Join Date
    Oct 2007
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you much!

  4. #4
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No it doesn't. But the element must exist, before it can be selected. When you put javascript code inside a <script> tag, it's executed, when the browser reads that part of the HTML. If your element is defined after the <script> tag, it doesn't exist, because the browser reads from top to bottom. The onload event is triggered after the page is loaded, so at that time, the element will exist. You can move the <script> tag to after the element, and any enclosing elements, for immediate execution.

  5. #5
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, it doesn't, but you can't find an element which doesn't yet exist.

    This will work:
    Code HTML4Strict:
    <p id="blah2">hello</p>
     
    <script type="text/javascript">
      var me = document.getElementById("blah2");
      alert(me.nodeName);
    </script>

    Edit:

    Beaten by seconds.
    Birnam wood is come to Dunsinane

  6. #6
    SitePoint Member
    Join Date
    Oct 2007
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ahh.. I see now. I just tried it and it worked. Thanks guys!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •