Skip to content Skip to sidebar Skip to footer

Best Approach To Handle "Cannot Read Property 'addEventListener' Of Null" Errors

Currently what I do is checking if element exist in page, but my code has a lot if conditions because of that. Jquery event listeners don't show errors when an element doesn't exis

Solution 1:

How jquery handles that...?

jQuery's API is set-based, not element-based. The DOM's API is element-based. When you do $("#foo").on("click", ...) in jQuery, if there's no element with the id "foo", $() returns an empty set, not null, and calling on on that set doesn't do anything, but doesn't cause an error either.

Since getElementById returns an element or null, you have to have the check you've shown to prevent trying to call methods on null, which causes an error.

If you want the benefits of a set-based API without using jQuery, you could write your own set of utility functions that use querySelectorAll to give yourself a thin set-based wrapper around the DOM API, if you like.

Here's a very simple starter example:

// The object we use as the prototype of objects returned by `domSet`
var domSetMethods = {
    on: function(eventName, handler) {
            // Loop through the elements in this set, adding the handler
            this.elements.forEach(function(element) {
                element.addEventListener(eventName, handler);
            });
            // To support chaining, return `this`
            return this;
        }
};
// Get a "DOM set" for the given selector
function domSet(selector) {
  // Create the set, usign `domSetMethods` as its prototype
  var set = Object.create(domSetMethods);
  // Add the elements
  set.elements = Array.prototype.slice.call(document.querySelectorAll(selector));
  // Return it
  return set;
}

domSet("#foo").on("click", function() {
  console.log("foo clicked");
});
// Notice that even though there's no id="bar" element, we don't get an error
domSet("#bar").on("click", function() {
  console.log("bar clicked");
});
<div id="foo">foo element (there is no bar element)</div>

You could add methods to domSetMethods that do other things. To support the chaining style of API jQuery provides, you return this in most cases from those methods.


Post a Comment for "Best Approach To Handle "Cannot Read Property 'addEventListener' Of Null" Errors"