简体   繁体   中英

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
  document.getElementById("bob");
  // ...
} else {
  alert('What kind of stupid browser are you using? Install a proper one');
}

This will return false :

if (document.getElementByID){} 

because there is no getElementByID on the document object. There is however, getElementById (notice the difference in the d at the end).

Therefore, this will return true

if (document.getElementById){} 

In short, if getElementByID exists on document, which because of the typing, does not, but if it did then do something.

A more full example using the right spelling:

if (document.getElementById) {
    // it is safe to use this method because it exists on document
    var element = document.getElementById('foo');
}

document.getElementById returns a function which evaluates to true when in an expression. You can test this out yourself but running the code snippet.

 console.log(document.getElementById); // The !! forces a boolean console.log(!!document.getElementById); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM