SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2009
    Posts
    60
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Very Simple Question about getElementById()

    I have a background with PHP and I'm now starting to learn javascript...

    When I use this following code:

    Code JavaScript:
    var bodyContent = document.getElementById("bodyContent");
    bodyContent.style.backgroundColor = "#ff0000";

    Theres an error because bodyContent shows up null
    However, once I place the same block of code in a function and add a button in the HTML with "onclick" the get.Element.ByID() works fine:

    Code JavaScript:
    function turnRed(){
    var bodyContent = document.getElementById("bodyContent");
    bodyContent.style.backgroundColor = "#ff0000";
    }
    Code HTML4Strict:
    <div id="bodyContent">
    	<button onclick="turnRed()" class="button">Red</button>
    </div>

    My simple question is, do you have to have getElementById in a function in order for it to be defined or am I simply missing something.

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, but the important thing here is that the browser will process the webpage from top to bottom. If you have any script in it, it will get executed immediately as it processes/parses from top to bottom. And if you put that code in the <head>, well that obviously gets executed well before it gets around to making any html elements.

    Wont work
    Code:
    <script>
    document.getElementById('foo');
    </script>
    <b id=foo></b>
    Works
    Code:
    <b id=foo></b>
    <script>
    document.getElementById('foo');
    </script>
    Generally, for multiple reasons, you try to avoid having javascript do any modifications to the dom until after the webpage has fully "loaded". A great way to do this is to put all your javascript right before the closing </body> tag.

  3. #3
    SitePoint Enthusiast
    Join Date
    Feb 2009
    Posts
    60
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ooh Ok,

    Thanks a lot that helps 100&#37;


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
  •