Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener() to non-existent elements?

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?

like image 991
Ram Patra Avatar asked Jul 18 '14 12:07

Ram Patra


People also ask

Is it better to use onclick or addEventListener?

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.

Is addEventListener the same as on ()?

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.

What is purpose of using addEventListener () method in JavaScript?

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.


1 Answers

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.

like image 83
Alnitak Avatar answered Sep 28 '22 20:09

Alnitak