Should I check if document.getElementById is set?
I came across some javascript code that first checks for existence document.getElementById
just before the more expected check for a specific element:
if (document.getElementById) {
var elem = document.getElementById("someid");
if (elem) {
...
}
}
Is this smart practice or hyperparanoia? And if it's reasonable, why not:
if (document && document.getElementById) { ... }
source to share
Every modern browser has this feature. I assume you were looking for very old JavaScript code from an era when it wasn't.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById Contains a table with compatibility information for a feature.
You don't need to validate the document or any of its more widely used functions in your code!
source to share
caniuse.com is a very useful site for this kind of thing. In this case, they are said to be supported "in all major browsers" and "safe to use". They provide a source where you can find it's supported:
- Chrome 1.0
- Firefox (Gecko) 1.0 (1.7 or earlier)
- IE 5.5
- Opera 7.0
- Safari (Webkit) 1.0
- Android 1.0
- Firefox (Mobile Gecko) 1.0 (1.0)
- IE Phone 6.0
- Opera Mobile 6.0
- Safari Mobile 1.0
source to share