简体   繁体   中英

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 an error like:

Cannot read property 'addEventListener' of null

I know why this happens, but I want to know whether there is a better way of attaching event listeners to elements that won't generate such errors?

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
});

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 || missing ensures that there's something present to absorb the addEventListener reference and invocation.

You have to be sure that element exist. So

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

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

Since ES2020

ES2020 introduced optional chaining and that feature is exactly what you need here:

document.querySelector('.class-name')?.addEventListener('click', ()=> console.log("Clicked"));

Supported in all modern up-to-date browsers.

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