I dynamically create a checkbox that has an EventListener. Unfortunately the EventListener doesn't work if I change the text of the checkbox-label with innerHTML
:
let label = document.createElement('label'),
input = document.createElement('input');
input.setAttribute('type', 'checkbox');
input.addEventListener('change', () => alert('Change Detected'));
label.appendChild(input);
document.body.appendChild(label);
label.innerHTML += 'Select Me!';
How can I circumvent this problem and why does it even exist?
Here a working snippet without the innerHTML
:
let label = document.createElement('label'),
input = document.createElement('input');
input.setAttribute('type', 'checkbox');
input.addEventListener('change', () => alert('Change Detected'));
label.appendChild(input);
document.body.appendChild(label);