I have attached a click
event listener on an element like:
document.querySelector('.class-name').addEventListener('click', function () {
});
The element may or may not get generated from the server-side.
So, if the server generates the element then all works fine but if not then i get a error like:
Cannot read property 'addEventListener' of null
I know why this happens, but I want to know whether there is any better way to attach event listeners to elements which won't generate such errors?
Summary: addEventListener can add multiple events, whereas with onclick this cannot be done. onclick can be added as an HTML attribute, whereas an addEventListener can only be added within <script> elements.
addEventListener() is a method of a normal DOM element and . on() is a jQuery object method. As you probably know, a jQuery object can represent more than one element and when you use the . on() method you are attaching and event handler to every element in the collection.
The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
There's no way of doing this without some sort of conditional test, but you can save a few characters compared to an if
block thus:
var el = document.querySelector('.class-name');
el && el.addEventListener(...);
I don't believe there's any simple way of avoiding the temporary variable (but see below).
NB: the below is included just to show that it's possible and should not be construed as a recommendation ;-)
If this is a very common pattern in your HTML and JS, a way to avoid the temporary assignment to el
is this:
var missing = {
addEventListener: function() {};
}; // a "null" element
(document.querySelector('.className') || missing).addEventListener(...);
The idea being that the || missing
ensures that there's something present to absorb the addEventListener
reference and invocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With