0

AddEventListener is not working for me. This is what I have tried:

const mtRemoveKeywords = document.querySelectorAll('.mt-remove-keyword');
for (let mtRemoveKeyword of mtRemoveKeywords) {
  mtRemoveKeyword.addEventListener('click', (e) => {
        alert('JS');
  });
}

I do not get an error message, so nothing happens. I guess this is because the selector is a dynamic element. I also tried it with windows.onload but that didn't help. The weird thing is that I have tried it with jQuery and that worked!

$(document).on('click', '.mt-remove-keyword', function() {
     alert('jQuery');
});

Why is it not working with Vanilla JS?

JSFiddle

Proseller
  • 113
  • 1
  • 8
  • Note your jquery version is using a delegated event listener, the event is actually attached to the document not the individual elements. That is why it works as the events triggered bubble up to the document. – Patrick Evans Sep 03 '20 at 13:27
  • 1
    It seems that those elements are not present in the page at the moment your vanilla JS is running. – Manuel Cheța Sep 03 '20 at 13:29

0 Answers0