50

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?

Arulkumar
  • 12,966
  • 14
  • 47
  • 68
Victor
  • 16,609
  • 71
  • 229
  • 409

3 Answers3

100
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.

Garrett
  • 1,658
  • 2
  • 17
  • 29
29

getElementById is defined by DOM Level 1 HTML to return null in the case no element is matched.

!==null is the most explicit form of the check, and probably the best, but there is no non-null falsy value that getElementById can return - you can only get null or an always-truthy Element object. So there's no practical difference here between !==null, !=null or the looser if (document.getElementById('xx')).

bobince
  • 528,062
  • 107
  • 651
  • 834
  • 2
    This should be the accepted answer since the only falsey value `getElementById` returns is `null`, there is no reason to check for any other value if you are only looking to check for existence. – cowbert Jan 29 '18 at 18:19
10

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');
Peter Rasmussen
  • 16,474
  • 7
  • 46
  • 63