0

Why does addEventListener only cooperate with the CANCEL label element and not the first, even if I remove the second? I don't get any error messages in console.

var ctrl = document.createElement('div');
ctrl.id = 'ctrl';

var showhide = document.createElement('label');
showhide.id = 'showhide';
showhide.innerHTML = 'Show/hide output';
showhide.setAttribute('onclick', 'return false;');
showhide.addEventListener("click", function() {
  alert('Show/hide');
});

var cancel = document.createElement('label');
cancel.id = 'cancel';
cancel.innerHTML = 'CANCEL';
cancel.setAttribute('onclick', 'return false;');
//document.getElementById('showhide').insertAdjacentHTML('afterEnd', cancel.outerHTML);
cancel.addEventListener("click", function() {
  alert('cancel');
});

ctrl.appendChild(showhide)
ctrl.innerHTML += ' | '
ctrl.appendChild(cancel)
document.body.appendChild(ctrl)
fivethous
  • 79
  • 2
  • 13
  • `ctrl.innerHTML += ' | '` doesn't append, it destroys everything in the element, and creates new content. The event listener was added to the original element, but not to the newly-created. – Teemu Feb 26 '17 at 19:46
  • huh! that was easy, thank you. Doesn't `+=` append? – fivethous Feb 26 '17 at 19:49
  • Nope, it's just a shortcut to `innerHTML = innerHTML + ' | '`. Use `insertAdjacentHTML` or create and append a textnode. – Teemu Feb 26 '17 at 19:50
  • Oh, alright. Thanks once again :) – fivethous Feb 26 '17 at 19:52

1 Answers1

1

The culprit in your above code is the line with ctrl.innerHTML += ' | '; Comment out the code and it will work fine. The reason is that when you use innerHTML the content is re-assigned and re-evaluated destroying the existing events. Here is an example explained in StackOverflow answers.

Community
  • 1
  • 1
debatanu
  • 766
  • 5
  • 11