Reputation: 7307
It is common for me to register javascript functions for certain events by doing something like:
myBtn.Attributes.Add("onClick", "Validate(getElementById('"+txtFirstName.ClientID + "'));");
I've always used getElementById
by itself, or in other words, sans document being prepended to it. But I'm having pages break on me lately when I try to use getElementById
instead of document.getElementById
. Why is this? Oddly, I have a website where one page allows me to use just getElementById
, but another other page throws a javascript error because it can't find the element if I do just getElementById
, and it'll only work if I do document.getElementById
.
Anyone know why this is? Should I be using document.getElementById
everywhere, regardless of whether it works without the document prefix?
EDIT: Could it have anything to do with the fact that one page is using AJAX and the other isn't?
Upvotes: 4
Views: 14914
Reputation: 27120
When you use getElementById()
and it works that mean that the function where it's called is running on the context of the document, that's is this == document.
So, you should ALWAYS use document.getElementById
to avoid that kind of errors.
Anyway, I would even stop using getElementById altogether and start using JQuery, i'm sure you'll never regret it.
Your code would look something like this if you used JQuery:
$("#myBtnID").click(function () { Validate($("#myTextboxID"))});
Upvotes: 7
Reputation: 66436
You should only use document.getElementById (even if I'd recommend using libraries like prototype or jquery to be able to use the $ sign).
If you are able to use getElementById on its own, it's just because the browser you're using is doing some kind of trick to get it to work, but the correct way is to use the document variable.
Upvotes: 1
Reputation: 3628
The correct way is indeed document.getElementById().
The reason (speculation) it might work by itself is that depending on where you use it the current context may in fact be the document object, thus inexplicitly resulting in document.getElementById().
Upvotes: 0
Reputation: 11444
Any function or variable you access without an owning object (ex: document.getElementById) will access the property from window.
So getElementById is actually window.getElementById, which isn't natively defined (unless you defined it before (ex: getElementById = document.getElementById).
Upvotes: 3
Reputation: 415600
You should use the full document.getElementById()
. If you find that too verbose, you could use jQuery:
$('#' + id)
or you could create an alias at the top of your script:
var byID = document.getElementById;
Upvotes: 1
Reputation: 404
I dont really know how to explain it but its because the getElementById() finds an element in the html structure of a page. Some browsers know that by default you want to search the document, but other browsers need that extra guidance hence document.
Upvotes: 0