Search code examples
javascriptdom-events

Uncaught TypeError: Failed to execute 'contains' on 'Node': parameter 1 is not of type 'Node'. at HTMLUListElement.<anonymous>


const icon = `<div class="container">
  <input type="checkbox" id="cbx2" style="display: none;">
  <label for="cbx2" class="check">
      <svg width="1.5rem" height="1.5rem" viewBox="0 0 25 25">
          <path d="M 1 9 L 1 9 c 0 -5 3 -8 8 -8 L 9 1 C 14 1 17 5 17 9 L 17 9 c 0 4 -4 8 -8 8 L 9 17 C 5 17 1 14 1 9 L 1 9 Z"></path>
          <polyline points="1 9 7 14 15 4"></polyline>
      </svg>
  </label>
</div>`
  li.innerHTML += icon

    todoUl.addEventListener("click", (e) => {
  const idAttr = e.target.closest("li").getAttribute("id")

  if (e.target.contains("check")) {
    e.target.parentElement.classList.toggle("checked")
    localStorage.setItem("todoList", JSON.stringify(todoList))
  } else if (e.target.classList.contains("fa-trash")) {
    e.target.parentElement.remove()
    todoList = todoList.filter((todo) => todo.id != idAttr)
    localStorage.setItem("todoList", JSON.stringify(todoList))
  }
})
# app.js:97 Uncaught TypeError: Failed to execute 'contains' on 'Node': parameter 1 is not of type 'Node'.
#   at HTMLUListElement.<anonymous>

I'm getting this error, it needs a very simple change but I couldn't figure it out. I want it to save the ticked button to localStorage and if the task completes I want it to work but when I refresh the page it goes back to its original state.


Solution

  • Node.contains() is an api that takes a Node and checks if it exists in the tester. Reference: https://developer.mozilla.org/en-US/docs/Web/API/Node/contains

    your problem use this code:

    todoUl.addEventListener("click", (e) => {
      const idAttr = e.target.closest("li").getAttribute("id")
    
      if (e.target.classList.contains("check")) {
        e.target.parentElement.classList.toggle("checked")
        localStorage.setItem("todoList", JSON.stringify(todoList))
      } else if (e.target.classList.contains("fa-trash")) {
        e.target.parentElement.remove()
        todoList = todoList.filter((todo) => todo.id != idAttr)
        localStorage.setItem("todoList", JSON.stringify(todoList))
      }
    })