-1

I'm trying to create a click event for my button to change the text decoration I keep getting this error under the done event listener.

This is my code-

let li = document.createElement('li');
let rmv = document.createElement('button');
let done = document.createElement('button');    
      
rmv.classList.add('remove-button');
done.classList.add('done-button');      
li.classList.add('li-item');
      
rmv.textContent = 'X';
done.textContent = '✔️';      
      
rmv.addEventListener('click', handleRemove);
      
done.addEventListener('click', function(){ 
  txt.style.textDecoration = "line-through";
})   
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • So, what is `txt`? Speculation: [What do querySelectorAll and getElementsBy\* methods return?](/q/10693845/4642212). – Sebastian Simon Jun 28 '21 at 16:37
  • Error is pretty clear : `txt` variable is `undefined`. – Flo Jun 28 '21 at 16:38
  • @Flo No, that’s not what the error says. `txt.style` is undefined. – Sebastian Simon Jun 28 '21 at 16:38
  • True, my bad :D btw as `txt` does not exists in that scope, it also is `undefined` hehe – Flo Jun 28 '21 at 16:40
  • @Flo Yes, `txt` does exist, the OP just didn’t show the relevant part of the code. If `txt` didn’t exist, the error would’ve been _“`ReferenceError`: '`txt`' is undefined”_. If `txt` was `undefined`, the error would’ve been _“`TypeError`: Cannot read property '`style`' of `undefined`”_. – Sebastian Simon Jun 28 '21 at 16:43
  • I actually defined txt earlier `let txt = document.createTextNode(input.value);` you can view the entire code here; https://codepen.io/kiva-gordon/pen/bGqaQxK – Kiva Gordon Jun 28 '21 at 16:44
  • @KivaGordon A text node doesn’t have a style. Only elements have styles. Create a `` instead: `const txt = Object.assign(document.createElement("span"), { textContent: input.value });`. – Sebastian Simon Jun 28 '21 at 16:48
  • @Mike'Pomax'Kamermans I have. This was a long time ago, so this was before I had my JavaScript gold badge and the close votes aged away long ago, probably. Not sure what the point of your comment is. – Sebastian Simon Mar 22 '22 at 22:00
  • Interesting, this question popped up as a new(ish) question on the front page me. – Mike 'Pomax' Kamermans Mar 22 '22 at 22:02
  • @Mike'Pomax'Kamermans Yes, because of the non-answer below. – Sebastian Simon Mar 22 '22 at 22:03

1 Answers1

2

This will fix it. It's better to utilize relative paths like this for dynamically created output. It gives you greater flexibility. To explain, e is the event of the click. The click listener always has a single argument event, and you can access the element that fired it with event.target. Then you find the closest 'li' container and apply the style to that. You can use the same logic to remove the element as well.

done.addEventListener('click', function(e){ 
  e.target.closest('li').style.textDecoration = "line-through";
})  
Kinglish
  • 23,358
  • 3
  • 22
  • 43