0

I'm working on simple Todo list app. When I click on X Id like to add a CSS class and after that Id like to delete that item with JavaScript; however, I want to wait for that animation to finish. My code looks like this:

let spans = document.querySelectorAll("span");
for (i = 0; i < spans.length; i++) {
  spans[i].addEventListener("click", function() {
    event.stopPropagation(); //stop bubbling effect
    this.parentElement.classList.add("fadeOut");
    setTimeout(function() {
      this.parentElement.remove(); //removing parent element with its contains
    }, 500)
  })
}
<li><span>X</span> Go sleep </li>

But I get the Uncaught TypeError: Cannot read property 'remove' of undefined at script.js:18 error. How do I pass that element I want to remove to function?

chazsolo
  • 6,692
  • 1
  • 15
  • 38
MadGrip
  • 111
  • 8

1 Answers1

0

Okay I ve declared const outside of the setTimeout function and it solved the problem, here is a code:

for(i = 0; i < spans.length; i++){
spans[i].addEventListener("click", function(){
    const el = this //Here I declare that constant
    event.stopPropagation();
    this.parentElement.classList.add("fadeOut");
    setTimeout(function(){
        el.parentElement.remove(); //removing parent element with its contains
    }, 500)
    
})}
MadGrip
  • 111
  • 8