Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
How to create a delete function for vanillajs todo list app?

Good day! I've been trying to figure out how to create a delete function in my todo app. I dont know what to do next and the delete function as well as the eventListener is not correct. I hope you guys can help me. I want to fully understand every small projects that I make. Thank you in advance! :)

const inputBox = document.querySelector('.input')
const addBtn = document.querySelector('.input-button')
const todoMain = document.querySelector('.todo-list')
const deleteBtn = document.querySelector('.delete-button')
const deleteAllBtn = document.querySelector('.clear-all')

//Event listeners 
inputBox.addEventListener("keyup", function(){
    let userInput = inputBox.value;
    if (userInput.trim() != 0) {
    addBtn.classList.add("active")
    } else {
        addBtn.classList.remove("active");
    }
})

addBtn.addEventListener("click", todoAdd);
todoMain.addEventListener("click", todoDelete);

// Functions
function todoAdd(event){
    event.preventDefault();

    const todoLi = document.createElement('li');
    todoLi.innerText = inputBox.value;
    
    const todoDeleteBtn = document.createElement('button');
    todoDeleteBtn.innerHTML = `<i class="fas fa-trash-alt"></i>`;
    todoDeleteBtn.classList.add('delete-button')
    todoLi.appendChild(todoDeleteBtn);

    todoMain.appendChild(todoLi);
    
    inputBox.value = '';

    addBtn.classList.remove("active");
};

function todoDelete(e){
    const item = e.target;
    if (item.classList[0] === 'delete-button'){
        todoMain.removeChild(todoLi);
    }
}
<link crossorigin rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
<div class="container">
    <h1>TODO list</h1>
    
    <div class="input-container">
        <input type="text" class="input" placeholder="Input Text Here">
        <button class="input-button"><i class="fas fa-plus"></i></button>
    </div>
    
    <ul class="todo-list">
    </ul>

    <div class="footer">
        <span>You have<span class="pending">0</span>pending task left</span>
        <button class="clear-all">Clear All</button>
    </div>
</div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There are a couple of issues that might be stopping this from working:

  1. Your function todoDelete tries to access the variable todoLi, which doesn't exist in its scope. You define this inside todoAdd, but its scope is limited so you can't access the variable from outside the function.

I suspect what you might want to be doing is passing item instead.

  1. You attach the event listener that triggers todoDelete to your todoMain element, which means that e.target for the function will always be the ul element, not your list element. Your if is then always false so the code never runs.

To fix this, attach the event listener to the todoDeleteBtn in your todoAdd function instead.

about 4 years ago · Juan Pablo Isaza Relatório

0

I have implemented it quite simply as an example.

When creating the ToDo item, I add a key for the text and a data attribute for the delete button and an onclick event.

The key is important to have the relation between button and text. First i used new Date() but i updated with an random Method. (Math.random()+1).toString().split('.')[1];

For deletAll() you can get the entire Parent Node and set html to an empty string.

const inputBox = document.querySelector('.input')
const addBtn = document.querySelector('.input-button')
const todoMain = document.querySelector('.todo-list')
const deleteBtn = document.querySelector('.delete-button')
const deleteAllBtn = document.querySelector('.clear-all')

//Event listeners 
inputBox.addEventListener("keyup", function(){
    let userInput = inputBox.value;
    if (userInput.trim() != 0) {
    addBtn.classList.add("active")
    } else {
        addBtn.classList.remove("active");
    }
})

addBtn.addEventListener("click", todoAdd);
todoMain.addEventListener("click", todoDelete);

// Functions
function todoAdd(event){
    event.preventDefault();

    const todoLi = document.createElement('li');
    const key =(Math.random()+1).toString().split('.')[1];
    todoLi.innerText = inputBox.value;
    todoLi.setAttribute("id", key);
    
    const todoDeleteBtn = document.createElement('button');
    todoDeleteBtn.innerHTML = `<i class="fas fa-trash-alt"></i>`;
    todoDeleteBtn.classList.add('delete-button')
    todoDeleteBtn.onclick = function() {
      const _key = this.getAttribute('data-key')
      document.getElementById(_key).remove();
      this.remove()
    }
    todoDeleteBtn.setAttribute("data-key", key);
    todoLi.appendChild(todoDeleteBtn);

    todoMain.appendChild(todoLi);
    
    inputBox.value = '';

    addBtn.classList.remove("active");
};

function todoDelete(e){
    const item = e.target;
    if (item.classList[0] === 'delete-button'){
        todoMain.removeChild(todoLi);
    }
}
<link crossorigin rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
<div class="container">
    <h1>TODO list</h1>
    
    <div class="input-container">
        <input type="text" class="input" placeholder="Input Text Here">
        <button class="input-button"><i class="fas fa-plus"></i></button>
    </div>
    
    <ul class="todo-list">
    </ul>

    <div class="footer">
        <span>You have<span class="pending">0</span>pending task left</span>
        <button class="clear-all">Clear All</button>
    </div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda