Document.getElementById () VS. getElementById ()

It is usually for me to register javascript functions for specific events, doing something like:

myBtn.Attributes.Add("onClick", "Validate(getElementById('"+txtFirstName.ClientID + "'));");

I always used getElementByIdby myself, or, in other words, a document was not attached to it. But lately, I have been having pages when I try to use getElementByIdinstead document.getElementById. Why is this? Oddly enough, I have a site on which one page allows me to use only getElementById, but the other other page causes a javascript error because it cannot find the element if I only do it getElementById, and it will work only if I do document.getElementById.

Does anyone know why this is? Should I use document.getElementByIdeverywhere, regardless of whether it works without a document prefix?

EDIT: Could this have anything to do with one page using AJAX and the other not?

+3
source share
6 answers

When you use getElementById(), and it works, it means that the function in which it is called is executed in the context of the document, that is, this document.

So, you should ALWAYS use document.getElementByIdto avoid such errors.

In any case, I would stop using getElementById altogether and start using jQuery , I'm sure you will never regret it.

Your code will look something like this if you used jQuery:

$("#myBtnID").click(function () { Validate($("#myTextboxID"))});
+7
source

, - (: document.getElementById), .

, getElementById window.getElementById, ( (: getElementById = document.getElementById).

+3

document.getElementById ( , jquery, $).

getElementById , , - , , - .

+1

document.getElementById(). , jQuery:

$('#' + id)

script:

var byID = document.getElementById;
+1

, , , getElementById() html . , , , , .

0

document.getElementById().

The reason (speculation) could be in itself that depending on where you use it, the current context may actually be a document object, so it implicitly leads to document.getElementById ().

0
source

Source: https://habr.com/ru/post/1708216/


All Articles