Home > Back-end >  How do i make the button that's also created with the list item work? I want it to delete the c
How do i make the button that's also created with the list item work? I want it to delete the c

Time:06-14

I tried to create an onclick event, but nothing happened

    let myWork = []
const submitEl = document.getElementById("submit-el")
const clearEl = document.getElementById("clear-el")
const listEl = document.getElementById("list-el")
const textEl = document.getElementById("text-el")

submitEl.addEventListener("click", function () {
    myWork.push(textEl.value)
    renderItems()

})

clearEl.addEventListener("click", function () {
    myWork.pop()
    renderItems()
})

function renderItems() {
    let listItems = ""
    for (let i = 0; i < myWork.length; i  ) {
        listItems  = `<li>${myWork[i]} </li> <button>Done</button>`
    }
    listEl.innerHTML = listItems
}

How do I make this button delete itself?

CodePudding user response:

If I understand your question, you want the "done" button delete its own line on click.

As a fast solution, you can write:

listItems  = `<li>${myWork[i]} </li> <button onclick="deleteWorkByIndex(${i})>Done</button>`

function deleteWorkByIndex(index) {
    myWork.splice(index, 1); // Delete the item n°{index}
    renderItems();
}
  • Related