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

192
Visualizações
How can I can keep the done Todo's from vanishing

I am trying to create a Todo list and wonder how I would go about keeping the completed todos from vanishing each time I add a new task. I am aware that this is happening because I clear my div each time a new task is added, however I am unsure on how to proceed for me to keep using arrays on this and still show completed tasks along with new tasks.

Codepen: https://codepen.io/martinkariuki7-the-looper/pen/OJvQXRW

const newToDo = document.getElementById('todo-new')
const addBtn = document.getElementById('addToDo')
const main= document.getElementById('toDoList')
const taskDone = document.getElementsByClassName('task')

let toDoList = []

// populate to do list
function populateToDo(){
  let todo = newToDo.value
  todo !== null && todo !== '' ? toDoList.push(todo) : alert('You must write something')

  updateDOM()
}

//Update DOM
function updateDOM(){
    // Clear main div
    main.innerHTML = `<h1>To do list </h1>`

    // Show tasks on the front
    toDoList.forEach(item =>{
        let task = document.createElement('div')
        task.classList.add('task')
        task.innerHTML = `<label><input type="checkbox" >${item}</label><br>`
        main.append(task)
   
        task.addEventListener('change', () => task.classList.toggle('task-complete'))

        newToDo.value = ''
    })

}

// Event listeners
// Add Tasks
addBtn.addEventListener('click', populateToDo)
newToDo.addEventListener('keydown', (e) => {
    if(e.code === 'Enter'){
       e.preventDefault()
       populateToDo()
    }
})
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want to use an array to update the list, you need to compare what you have with what will be changed.

If there aren't items with the same text, you could do something like this:

function updateNodes()
{
    const nodesMap = new Map();
    [...document.querySelectorAll('div label')]
        .forEach(node => {
            nodesMap.add(node.innerText, node);
        });
  
    const nodesUpdate = [];
    toDoList.forEach(item => {
        if (nodesMap.has(item)) {
            nodesUpdate.push(nodesMap[item]);
        } else {
            const newNode = document.createElement('div');
            newNode.classList.add('task');
            newNode.innerHTML = `<label><input type="checkbox" >${item}</label>`;
            nodesUpdate.push(newNode);
        }
    });
  
    return nodesUpdate;
}

Otherwise, each item (or task) needs to have an identification. Otherwise, if there are two items with the same name, you won't know which one was removed or moved. Besides, without identifications, you can't know if an item was renamed.

The code here was not tested and, of course, you need to adapt it to your needs.

about 4 years ago · Santiago Trujillo 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