Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 249
Victor Avatar asked Mar 27 '13 18:03

Victor


People also ask

Why is my document getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

What does document getElementById return if not found?

HTML DOM Document getElementById() The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.

How do I fix document getElementById is not a function?

To solve the "getElementById is not a function" error, make sure to spell the getElementById() method correctly, as it is case-sensitive, and only call the method on the document object, e.g. document. getElementById('btn') . Copied!


1 Answers

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.

like image 98
Garrett Avatar answered Sep 28 '22 01:09

Garrett