Reputation: 314
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?
Upvotes: 0
Views: 401
Reputation: 18908
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);
Upvotes: 1
Reputation: 288680
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');
}
Upvotes: 4