Skip to content Skip to sidebar Skip to footer

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 gen

Solution 1:

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.

Solution 2:

Just check before if your element is here or not (like in comment ) :

var el = document.querySelector('.class-name');
if (el) { el.addEventListener(...); }

Edit : You can also wrap your element .class-name into a div and do something like that :

document.getElementById("myDiv").addEventListener("click",function(e) {
    var classes = e.target.className;
    if(classes = ".class-name")
        //DO SOMETHING
});

Solution 3:

You have to be sure that element exist. So

var element = document.querySelector('.class-name');

if (element)
   element.addEventListener('click', function () {});

Post a Comment for "Addeventlistener() To Non-existent Elements?"