Best Approach To Handle "cannot Read Property 'addeventlistener' Of Null" Errors
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 handlerthis.elements.forEach(function(element) {
element.addEventListener(eventName, handler);
});
// To support chaining, return `this`returnthis;
}
};
// Get a "DOM set" for the given selectorfunctiondomSet(selector) {
// Create the set, usign `domSetMethods` as its prototypevar set = Object.create(domSetMethods);
// Add the elements
set.elements = Array.prototype.slice.call(document.querySelectorAll(selector));
// Return itreturn 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 errordomSet("#bar").on("click", function() {
console.log("bar clicked");
});
<divid="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"