简体   繁体   中英

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 exist. How does jQuery handle that and what techniques can I use for better design?

var el = document.getElementById('el');
var another_el = document.getElementById('another_el');

if(another_el){
el.addEventListener('click', swapper, false);
}

if(el){
  el.addEventListener('click', swapper, false);
}
....
...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM