Reputation: 45
I am currently in need of using vanilla.js in my application because of html entities that come from the database and I need to treat them. Because the babel compilation has already ended, I am doing this using the DOM. I am trying to set an icon inside a span, and whenever I click this icon, I want to remove the whole span. The thing is, I can create this icon and set its attributes as fontSize and so on, but when it comes to the onclick function, it just doesnt work, the function is not activated by the click. I already tried using a callback function inside it, a vue function and so on. But the event is not activated whatsoever. What could I do?
icon.classList.add("material-icons", "cancel_icon")
icon.innerHTML = "cancel"
icon.style.fontSize = '14px'
icon.style.position = 'relative'
icon.style.top = '2px'
icon.style.left = '2px'
icon.onclick = () => this.removeSpan(span)
console.log(icon.onclick)
return span
Upvotes: 1
Views: 328
Reputation: 6878
you can try span.childNodes[0]
or span.firstChild
span.firstChild.addEventListener('click', this.removeSpan);
one way if you want to pass a parameter to a listener function is do as you try with an intermediate callback
let _this = this;
span.firstChild.addEventListener('click', () => {
_this.removeSpan(span);
});
Upvotes: 2