Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById() VS. getElementById()

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?

like image 811
Jagd Avatar asked Nov 05 '25 21:11

Jagd


1 Answers

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"))});
like image 183
albertein Avatar answered Nov 08 '25 12:11

albertein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!