/    Sign up×
Community /Pin to ProfileBookmark

getElementById pains

I try to reference an element, specificially to add on event (using addEventListener) but it keeps saying the element is “null” or “undefined” example:

var element = getElementById(‘inputbox’);
element.addEventListener(‘keyup’, someFunction, true);

what is weird is, it won’t work in the script but if I try to reference the element [I]the exact same way[/I] in Chrome’s Element Inspector or Firebug everything works just fine.

any suggestions?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@MTputer_comJun 01.2009 — What type of element are you trying to reference? I had the same error when I tried to reference an <embed> element until I figured out that <embed> does not support the ID attribute. Maybe give me a few more details.

Also, I try to avoid creating variables that use the same word as JavaScript language..."element". Try "myElem" or something else you just create out of thin air that won't get mistaken as code.

Jeff
Copy linkTweet thisAlerts:
@Y_LessJun 01.2009 — Is your script before the element? If it's run before all of the page (or at least the element you're trying to access) is loaded you can't use it as it doesn't exist yet.
Copy linkTweet thisAlerts:
@astupidnameJun 01.2009 — var element = getElementById('inputbox');[/QUOTE]
getElementById is not a property of the window object, unless you have defined your own, but is property of document and of the document's elements'. In addition to what Y_Less says about making sure the element exists when trying to access it, change the above to:
[CODE]var element = [COLOR="Red"]document.[/COLOR]getElementById('inputbox');[/CODE]
Copy linkTweet thisAlerts:
@JeremyHappensauthorJun 01.2009 — Thank you for all the great and speedy responses!

I had been calling the script in the <head> tag, moving it below [B]all[/B] of my html turned out to fix it. I honestly didn't know you could call <script> tags anywhere else but between <head> and </head>.

Thank you for all your other information about the getElementById method, hopefully I can avoid future problems.
×

Success!

Help @JeremyHappens spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...