1

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
1
  • Does your vanilla JS code work if you use it outside of Vue? Commented Nov 26, 2021 at 16:13

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

6 Comments

Yup, that didn't work.
i edit my reply with other element that may help you. your callback is working on my side. do you have no execution or an error message ?
Didn't work as well :c no, no errors
Have you got news about this issue ? do you notice that this in the callback match to another context that the class where you recover method removeSpan ?
Well, the only thing that didn't work was the onclick function attribution. So what I did is to bind the function in the element inside the updated hook.. that worked.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.