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) { ... }

      

+3


source to share


3 answers


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!

+2


source


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
+3


source


This is basic feature detection. The disadvantage of this code is the lack of competent degradation. It should do something like:

if (feature) {
    // Use it
} else {
    // Graceful alternative
}

      

Speaking, getElementById

it is widely available, so for me it's an antique code.

+2


source







All Articles