create a div with elements if it is nested under a specific style

I can’t figure why the order of my replaceChild fires off before the condition is met. I want to replace a specific child element when it gets moved to a different container with another element suited for that container. This is happening inside a function that checks to see which buttons are clicked. When the check mark button is clicked. It will move the entire list item from a div called tasklist to a div called completed. Any help is appreciated. Here is my code:

function statusCheck(e) {
const item = e.target;

if (item.classList.contains('trash-btn')) {
    const task = item.parentElement.parentElement;
    task.classList.add('vanish');
    task.addEventListener('transitionend', function(){
        task.remove();
    });
}

if (item.classList.contains('check-btn')) {
    let task = item.parentElement.parentElement;
    task.classList.add('complete');
    item.remove();
    completed.appendChild(task);

    task = document.querySelector('.complete');
    const taskItem = document.querySelector('.card-date');
    if (task.classList.contains('complete')) {
        console.log(taskItem);
        const swapTask = taskItem.children[0];
        console.log(swapTask);
        const swapTaskItem = document.createElement('span');
        swapTaskItem.classList.add('text-complete');
        swapTaskItem.innerText = 'Completed: ';
        taskItem.replaceChild(swapTaskItem, swapTask);
    }
}

This picture shows Completed before moving to my completed div. Sometimes they stack in the Done column with a ‘Completed: Completed:’

enter image description here

>Solution :

I’d suggest a different direction. Using the DOM to track application state isn’t a great strategy. I would keep a state object for your tasks and refer to that instead. Data-driven DOM rather than vice-versa. This is, in general terms, what front-end app libraries like React, Angular, and Vue do for you. You can approximate that functionality with something like this:

let items = [{
  id: 1,
  assignedTo: '',
  description: '',
  dueDate: '',
  completed: false
}, {
  id: 2,
  assignedTo: '',
  description: '',
  dueDate: '',
  completed: false
}, {
  id: 3,
  assignedTo: '',
  description: '',
  dueDate: '',
  completed: false
}];

Then, rather than moving elements around and updating classes, you’d update properties in each task object as needed, and you’d refresh your view by re-mapping them:

items.map(item => {
  // put items into the page as appropriate
});

Leave a Reply