document.getElementById isn't working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • risk32
    New Member
    • Mar 2008
    • 98

    #1

    document.getElementById isn't working

    Hi all. I'm not exactly sure what I'm doing wrong, but when I try to use the document.getEle mentById() method, it's not working. Here's what I have:

    Code:
    var username = document.getElementById('username')
    
    function test()
    	{
    		document.write(username)
    	}
    
    ...
    
    Username: <input type="text" id="username">
    <input type="button" value="test" onClick="test();">
    (I am aware that I don't use braces in standard format, it just helps me keep track of what I'm doing)

    When I click the button, the only thing it returns is null. Am I doing something wrong?
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    yes and no. if you call getElementById( ) before the document tree is finished (resp. the element in questions is attached to the DOM) you get null as result.

    Comment

    • risk32
      New Member
      • Mar 2008
      • 98

      #3
      Originally posted by Dormilich
      yes and no. if you call getElementById( ) before the document tree is finished (resp. the element in questions is attached to the DOM) you get null as result.
      Where would be the appropiate location for the document.getEle mentById() method?

      Comment

      • risk32
        New Member
        • Mar 2008
        • 98

        #4
        I actually feel like an idiot. Even though the variable was assigned globally, it didn't read inside the function. So, I put it inside the function and added .value to the end for the alert. It's working. Now to figure out arrays...

        Comment

        Working...