1

I have a single javascript where I have declared all my variables in the

$(document).ready(function(){
    //variables
});

The values of these variables are initialized as well and mostly they are HTML elements. The elements are determined using the ids via document.GetElementById(). Some of these elements exists only in a different page which is not loaded in the browser yet. This results in null error when the variables holding the elements are used for a different purpose.

var container_element = document.getElementById('unique-id');
var count = container_element.getElementsByTagName("div").length;

Since the element with "unique-id" is present in another page which is not loaded in the browser, the second line would return an error because container_element is null. To fix this, I changed the code to

var container_element = document.getElementById('unique-id');

if(container_element) {
    var count = container_element.getElementsByTagName("div").length;
}

Is this is the only way to handle such a thing? Should I have to do a null check for every function that I invoke via a variable or is there any other solution or standard / best practice?

bits-bytes
  • 77
  • 1
  • 9
  • Yes, that is the general idea. If you don't know if you'll have an actual element or not, you check with a condition. – adeneo Sep 04 '17 at 17:24

1 Answers1

3

You need a guard like that any time the element may or may not exist as of when you use getElementById. You can use the if you've shown, or

var container_element = document.getElementById('unique-id');
var count = !container_element ? 0 : container_element.getElementsByTagName("div").length;

or similar.

Another option is to react to the exception:

var container_element = document.getElementById('unique-id');
var count;
try {
    count = container_element.getElementsByTagName("div").length;
} catch (e) {
    count = 0;
}

I notice you're using jQuery but not using it in that code. Which is too bad, because if you were, jQuery's set-based nature would mean you didn't need the guard:

var container_element = $('#unique-id');
var count = container_element.find("div").length;

Even though container_element is an empty set, you can call methods on it. Most jQuery methods provide intelligent handling of empty sets. For instance, using find on an empty set returns a (new) empty set, as above.

You still have the option to know whether the element exists (more in this question's answers):

if (container_element[0])
// or
if (container_element.length)
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875