0
const list = document.getElementById('list')
const addtodo = document.getElementById('addtodo')
//const items = document.querySelector('.item')
const deleteItem = document.querySelector('.delete')
addtodo.addEventListener('keypress', submitTodo)

function submitTodo(event) {
    if (event.keyCode == 13) {
        event.preventDefault()
        let value = addtodo.value
        let li = document.createElement('li')

        li.innerHTML = `
        <img class="unchecked" src="icon/unchecked.svg" /> 
        ${value}
        <img class="delete" src="icon/icons8-multiply-26.png" /> `

        list.appendChild(li)
    }
}

deleteItem.addEventListener('click', items)


function items(item) {
    if (item.target.classList.contains('delete')) {
        item.target.parentElement.remove()
    }
}

The code above only allows me to delete one item and its the first one on the list I try to solve it on my own but couldn't any idea whats wrong

ES Sinc
  • 41
  • 4

2 Answers2

2

When deleteItem.addEventListener('click', items) is ran, it only attaches the eventListener to the elements currently on the DOM - the ones you create dynamically will not have this eventListener

You can use 'event delegation' instead to listen for clicks, and filter theses clicks based on if the click was coming from the correct element

You can read more about event delegation from davidwalsh's blog and this StackOverflow answer

document.addEventListener('click', function(e) => {
  if(e.target && e.target.classList.includes('delete')){
    e.target.parentElement.remove() 
  }
});

You could also make use of the elements onclick attribute, and pass this in the parameter of the function call - this way you can access the HTML Element directly from the parameter; this also avoids having to have an eventListener, or using an if to check if it's the correct class / ID

// Add the function to the onclick attribute of the img
<img class="delete" onclick="deleteItem(this)" src="demo.png" />

// in this function, 'item' refers to the DOM Element that was clicked
function deleteItem (item) {
  item.parentElement.remove();
}
Shiny
  • 4,654
  • 3
  • 12
  • 29
0

This code will allow you to remove the first element on ul .

let list = document.getElementById("list"); // ul element
let remove = document.getElementById("remove"); // remove button

// on double click event
remove.onclick = () => {
  // remove the first child from the list
  list.removeChild(list.firstChild);
}
<ul id="list">
  <li>One</li>  
  <li>Two</li>
  <li>three</li>
</ul>
<input type="button" id="remove" value="Remove First"></input>
Ayman Ben
  • 25
  • 3