document.getelementbyId will return null if element is not defined?

Victor picture Victor · Mar 27, 2013 · Viewed 116.6k times · Source

In my code, I see this:

if (document.getElementById('xx') !=null) {
    //do stuff
}

if xx element is not defined, will this evaluate to true or false?

Should I write:

if (document.getElementById('xx'))

to be safe?

Answer

Garrett picture Garrett · Mar 27, 2013
console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.