SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Nov 2007
    Posts
    117
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    getElementByID questions

    Hi,

    I have the following code which only works when I use a <p> tag rather than <div> tag.

    Is there a reason why a <div> doesn't work?

    Thanks

    PHP Code:
    <script>
    function 
    displayDate()
    {
    document.getElementByID("test") .innerHTML=Date();
    }
    </script>

    <button type="button" onclick="displayDate()">test</button>
    <p id="test">
    show date
    </p> 

  2. #2
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,101
    Mentioned
    448 Post(s)
    Tagged
    8 Thread(s)
    It shouldn't make a difference. You do have two errors in your code, though: ID instead of Id, and a gap before .innerHTML. Try this instead:

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    </head>
    <body>
    
    <button type="button" onclick="displayDate()">test</button> 
    <div id="test"> 
    show date 
    </div>  
    
    <script> 
    function displayDate() { 
    	document.getElementById("test").innerHTML=Date();
    } 
    </script> 
    </body>
    </html>
    or this

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    </head>
    <body>
    
    <button id="button" type="button">test</button> 
    <div id="test"> 
    show date 
    </div>  
    
    <script> 
    var button = document.getElementById("button");
    var test = document.getElementById("test");
    button.onclick = function displayDate() {
        test.innerHTML = Date();
    }
    </script> 
    </body>
    </html>
    Facebook | Google+ | Twitter | Web Design Tips | Free Contact Form

    Forum Usage: Tips on posting code samples, images and more

    Forrest Gump: "IE is like a box of chocolates: you never know what you're gonna get."

  3. #3
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,873
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    The code will work with both a <div> and a <p> and any other element that you can attach an id to.

    I think the problem is that you have a typo in your code.

    This:

    Code JavaScript:
    document.getElementByID("test") .innerHTML=Date();

    should be this:

    Code JavaScript:
    document.getElementById("test").innerHTML=Date();

    Hope that helps.

    Edit: Oops. Ralph was quicker.


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
  •