Tomkarho
Tomkarho

Reputation: 1817

Preventing "cannot set property of null" in JavaScript

Now I have several elements bound to variables and different actions are done with these elements. However every now and then it happens that the script handling these elements is triggered in a place where these elements do not exist (I do not have the power to change this atm). As such whenever the script tries to run the script it gives Cannot set property XXXXX of null and thus the script fails.

Now I know I can prevent this failure by checking for the existence of the variable like so:

var elem = document.getElementById('myelement');

if (elem){
// do something
}

However since there are multiple elements with different actions bound to them I would have to do the check to each one of them meaning writing multiple if clauses:

var elem = document.getElementById('myelement');
if (elem){
    // do something
    }

var anotherElement = document.getElementById('another');
if (anotherElement){
    // do something different
    }

var oneMoreElement = document.getElementById('onemore');
if (oneMoreElement){
    // do something even different
    }

Even with this small example one can see that there are a lot of repeting code there, which I would like to eliminate if possible.

Is there some way to make this kind of scenario work more smoothly?

Upvotes: 0

Views: 237

Answers (3)

user948581
user948581

Reputation:

You could factorize your code, so that a loop contains the common parts, and an ad-hoc array contains the variables AND specific behaviour/parameters. For instance:

var items = [['myelement','foo'],['another','bar'],['onemore','foobar']];
for (var i in items ) {
    var item = elements[i];
    var e = document.getElementById(item[0]);
    if (e) {
        alert(item[1])
    }
}

Of course, the way you shape your array and what it contains heavily depends on your scenario. Here the variables associated with an element are only strings, but it could be callables, arrays, dictionaires, etc.

Note that as others have said, you could put the common part in a separate function. But I think the real trick here is to think in terms of factorization.

Upvotes: 0

Satpal
Satpal

Reputation: 133433

You can use something like

function ifElementExistExecute(id, callback){
    var element = document.getElementById(id);
    if (element){

        //Additionally check callback is a function
        if (typeof(callback) == "function") {
            // do something
            callback(element);
        }
    }
}

Usage

ifElementExistExecute('myelement', function(element){
    //do something
});

Upvotes: 2

A Paul
A Paul

Reputation: 8261

you can just write a function like below

function checkElementExist(var elementID) {
  var elem = document.getElementById(elementID);
  if (elem){
    return true;
  }
  return false;
}

Now when you code check

checkElementExist('myelement') // or any element

Upvotes: 0

Related Questions