Originally I was doing this:
button.addEventListener('click', function(e) {
e.preventDefault();
var clickedButton = this;
}
However, I need to listen out for a button which is dynamically added to the DOM. So now I am doing this:
document.addEventListener('click', function(e) {
if (e.target.nodeName == "BUTTON") {
e.preventDefault();
var clickedButton = e.target;
}
}
This works in the case of:
<button>Click me</button>
However, it doesn't work with:
<button><i class="icon"></i></button>
The reason it doesn't work is because e.target
ends up as I
instead of BUTTON
, however I need to specifically target the button. Some buttons might contain an icon, whilst others might be just text, and some could be a combination of the two.