view raw
user6534060 user6534060 - 8 months ago 38
Javascript Question

Cannot read property 'value' of null. when i'm in other pages

in my website i use one javascript file called " backend.js "
contain javascript/jquery codes for all the website pages

so, for example in a function with a line like this :

var latit = document.getElementById('lat').value;

it works fine on a page that contains id='lat'
but in other pages i got this error in console :

Uncaught TypeError: Cannot read property 'value' of null

and also with style :

Uncaught TypeError: Cannot read property 'style' of null

and it causes stop of executing my other functions below the line.

the same with any line with
code in all my file.

i found a solution but i don't know if it's the best or there is better

my solution it to make a test for any
in my file like this :

if (document.getElementById('lat') != null) {
var latit = document.getElementById('lat').value;

is it the best solution ?


No need to call getElementById twice. You can store the result of the first call in a variable.

var lat = document.getElementById('lat');
if(lat) {
  var latit = lat.value;

If you don't want additional variables, you can also use

var latit = (document.getElementById('lat') || {}).value;

or || Object.create(null) if you are afraid Object.prototype.value might exist.