0

I'm creating my first project from scratch (no tutorial) and have run into an issue. I'm trying to allow an li to be clicked when finished to cross it off. I know kind of what i have to do, but when i create a event listener for it, what do i reference since the button and li is created after the user submits an input, i can't exactly call on it, or at least don't know how to.

So basically what im trying to do is this:

  1. create LI
  2. create button
  3. give LI the class that allows it to be crossed out
  4. toggle the class on and off depending on if its been clicked or not

This is what i have so far and i create the li and the button but when i assign it the class, it's automatically applied and I'd like to toggle it.

function addNewTodo() {
  //create a new list item
  let li = document.createElement('li');
  li.className = 'list-check';
  //grab the value from the form
  let inputValue = document.getElementById('newtodo').value;
  let task = document.createTextNode(inputValue);
  //create a button to allow the removal of an item
  let button = document.createElement('button');
  button.innerHTML = 'Remove';
  li.appendChild(task);
  li.appendChild(button);
  tasks.push(newtodo.value);
  if (inputValue === '') {
    alert("You must write something!");
  } else {
    document.getElementById("ul").appendChild(li);
    totalItems++;
  }

Thanks so much for the help

ValLeNain
  • 2,232
  • 1
  • 18
  • 37

1 Answers1

0

You can have the eventlistener on the ul, event.target will references the real li clicked. Here is a good example

Or you can also add an eventListener to li right after creating it.

farvilain
  • 2,552
  • 2
  • 13
  • 24