Nicole Cook Nicole Cook - 5 months ago 10
Javascript Question

When document.getElementByID is used without an ID what is it doing?

I have some code I am looking at that is using a variation on getElementByID that I do not understand. I have looked online but I am not finding anything that explains this.

I understand how to use something like document.getElementByID("bob"), however what I am looking at says:

if (document.getElementByID){}

When you use getElementByID in this fashion what is it doing?


document.getElementById returns the function which can be used to get some element by ID.

typeof document.getElementById; // 'function'

However, if some browser didn't implement getElementById, you would get undefined.

Therefore, this is just a test to ensure that the method exists before calling it, avoiding an error.

if(document.getElementById) {
  // Hopefully it's safe to call it
  // ...
} else {
  alert('What kind of stupid browser are you using? Install a proper one');