0

I'm trying to make a todo list, with two functions (markAsDone and deleteAfterClick) and I managed to make them work. But when I add new li elements, those function don't work with them.

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.querySelectorAll("li");
var btn = document.querySelectorAll(".btn");

function inputLength() {
  return input.value.length;
}

function createListElement() {
  var li = document.createElement("li");
  var btn = document.createElement("button");
  var i = document.createElement("i");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);
  li.appendChild(btn);
  btn.appendChild(i);
  btn.classList.add("btn");
  i.classList.add("fa", "fa-trash");
  input.value = "";
}

function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}

function addListAfterKeypress(event) {
  if (inputLength() > 0 && event.keyCode === 13) {
    createListElement();
  }
}

function markAsDone() {
  for (let i = 0; i < li.length; i++) {
    li[i].addEventListener("click", function () {
      li[i].classList.toggle("done");
    });
  }
}

function deleteAfterClick() {
  for (let i = 0; i < btn.length; i++) {
    btn[i].addEventListener("click", function () {
      li[i].parentNode.removeChild(li[i]);
    });
  }
}

markAsDone();
deleteAfterClick();

button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    Could you elaborate on "those function dont work with them?" To me, it could mean a number of things. – Rojo Jan 11 '21 at 22:21
  • 2
    They don't work because the new `li` elements don't exist when you search for `li` elements and set up the handlers. Instead, use ["event delegation"](https://stackoverflow.com/questions/65645404/event-listener-on-list-of-html-elements/65645519#65645519) which solves the problem and greatly simplifies the code. – Scott Marcus Jan 11 '21 at 22:25
  • 1
    THANKS! @ScottMarcus. After researching "event delegations", ive finally make it work – Daniel Jimenez Jan 13 '21 at 16:43

0 Answers0