A reference to an element will never look “falsy”, so leaving off the explicit null check is safe.
Javascript will treat references to some values in a boolean context as false
: undefined, null, numeric zero and NaN
, and empty strings. But what getElementById
returns will either be an element reference, or null. Thus if the element is in the DOM, the return value will be an object reference, and all object references are true
in an if ()
test. If the element is not in the DOM, the return value would be null
, and null
is always false
in an if ()
test.
It’s harmless to include the comparison, but personally I prefer to keep out bits of code that don’t do anything because I figure every time my finger hits the keyboard I might be introducing a bug 🙂
Note that those using jQuery should not do this:
if ($('#something')) { /* ... */ }
because the jQuery function will always return something “truthy” — even if no element is found, jQuery returns an object reference. Instead:
if ($('#something').length) { /* ... */ }
edit — as to checking the value of an element, no, you can’t do that at the same time as you’re checking for the existence of the element itself directly with DOM methods. Again, most frameworks make that relatively simple and clean, as others have noted in their answers.