How to delete a TODO item list from DOM when I click delete button using JavaScript?

48 Views Asked by At

In delete function of TODO item I want to delete a specific todo item with given id but I am having difficulty in selecting parent i.e. div tag in which I have stored the title description and delete button which I am adding by sending a request using JavaScript. Problem how to delete div tag of specific delete button having id using removeChild()? How to do that?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TODO app</title>
</head>
 <script>

    function deleteDone(id) {
        console.log("Deleted todo ID:", id);
        // Delete the right todo from the list
        // You will need to give each todo an id, and that should be enough to remove it
      

    }
    function deleteTodo(id) {
        fetch("http://localhost:3000/todos/" + id, {
            method: "DELETE",
            headers: {
                "Content-Type": "application/json"
            }
        }).then(deleteDone)
    }


    function getTodoscallBack(data){
        console.log(data);
        var parentElement = document.getElementById("mainArea");
        // parentElement.innerHTML = JSON.stringify(data);
        for(var i=0;i<data.length;++i){
            var childElement = document.createElement("div");

            var grandChildren1 = document.createElement("span");
            grandChildren1.innerHTML= data[i].title;
            var grandChildren2 = document.createElement("span");
            grandChildren2.innerHTML= data[i].description;
            var grandChildren3 = document.createElement("button");
            grandChildren3.innerHTML="Delete";
            grandChildren3.setAttribute("onclick","deleteTodo("+data[i].id+")");
            
            childElement.appendChild(grandChildren1);
            childElement.appendChild(grandChildren2);
            childElement.appendChild(grandChildren3);
            
            parentElement.appendChild(childElement);

        }
        
    }
    function callbackFn2(res){
        res.json().then(getTodoscallBack);
    }
    function getData(){
        fetch("http://localhost:3000/todos",{
            method:"GET",
        }).then(callbackFn2);
            
    }

    getData();
    function parsedResponse(data){
        console.log(data);
        var parentElement = document.getElementById("mainArea");
        var childElement = document.createElement("div");

            var grandChildren1 = document.createElement("span");
            grandChildren1.innerHTML= data.title;
            var grandChildren2 = document.createElement("span");
            grandChildren2.innerHTML= data.description;
            var grandChildren3 = document.createElement("button");
            grandChildren3.innerHTML="Delete";
            
            childElement.appendChild(grandChildren1);
            childElement.appendChild(grandChildren2);
            childElement.appendChild(grandChildren3);
            
            parentElement.appendChild(childElement);
    }
    function callback(res){
        res.json().then(parsedResponse);
    }
  
      function onPress(){
        var  title = document.getElementById("title").value;
        var  description = document.getElementById("description").value;
        
        console.log(title,"\n",description);

        fetch("http://localhost:3000/todos",{
            method:"POST",
            body: JSON.stringify({
                title: title,
                description:description
            }),
            headers: {
                "Content-Type": "application/json"
            }
        }).then(callback);
    }


 </script>
<body>
    
    Todo title
    <input type="text" id="title"></input>
    <br><br>
    Todo description
    <input type="text" id="description"></input>
    <br><br>
    <button onclick="onPress()">send todo</button>
    <div id="mainArea">

    </div>
</body>
</html>
1

There are 1 best solutions below

2
Diego D On

I copied your same exact code and passed a bogus array modeling the todo as you did already

const todos = [{
    id: 1,
    title: 'title#1',
    description: 'description#1'
  },
  {
    id: 2,
    title: 'title#2',
    description: 'description#2'   
  }];

To remain consistent with your strategy, in your logic creating the todo items, I added the feature of setting the data-id attribute of each delete button with the corresponding todo id, and then inside the deleteDone function I fetched the clicked delete button using an attribute selector and later removed the whole div container retrieved using closest.

const todos = [{
    id: 1,
    title: 'title#1',
    description: 'description#1'
  },
  {
    id: 2,
    title: 'title#2',
    description: 'description#2'   
  }];

getTodoscallBack(todos);


function deleteDone(id) {
  console.log("Deleted todo ID:", id);

  //retrieves the delete button holding the data-id attribute passed
  const delButton = document.querySelector(`[data-id="${id}"`);
  //retrieves the element containing that button
  const todoContainer = delButton.closest('div');
  //removes the whole div containing the todo
  todoContainer.remove();

}

function deleteTodo(id) {
  /*
  fetch("http://localhost:3000/todos/" + id, {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json"
    }
  }).then(deleteDone)
  */
  deleteDone(id);
}


function getTodoscallBack(data) {
  console.log(data);
  var parentElement = document.getElementById("mainArea");
  // parentElement.innerHTML = JSON.stringify(data);
  for (var i = 0; i < data.length; ++i) {
    var childElement = document.createElement("div");

    var grandChildren1 = document.createElement("span");
    grandChildren1.innerHTML = data[i].title;
    var grandChildren2 = document.createElement("span");
    grandChildren2.innerHTML = data[i].description;
    var grandChildren3 = document.createElement("button");
    grandChildren3.innerHTML = "Delete";
    grandChildren3.setAttribute("onclick", "deleteTodo(" + data[i].id + ")");

    //HERE I set the data-id attribute value as data[i].id
    grandChildren2.dataset.id = data[i].id;

    childElement.appendChild(grandChildren1);
    childElement.appendChild(grandChildren2);
    childElement.appendChild(grandChildren3);

    parentElement.appendChild(childElement);

  }

}

function callbackFn2(res) {
  res.json().then(getTodoscallBack);
}

function getData() {
  fetch("http://localhost:3000/todos", {
    method: "GET",
  }).then(callbackFn2);

}

getData();

function parsedResponse(data) {
  console.log(data);
  var parentElement = document.getElementById("mainArea");
  var childElement = document.createElement("div");

  var grandChildren1 = document.createElement("span");
  grandChildren1.innerHTML = data.title;
  var grandChildren2 = document.createElement("span");
  grandChildren2.innerHTML = data.description;
  var grandChildren3 = document.createElement("button");
  grandChildren3.innerHTML = "Delete";

  childElement.appendChild(grandChildren1);
  childElement.appendChild(grandChildren2);
  childElement.appendChild(grandChildren3);

  parentElement.appendChild(childElement);
}

function callback(res) {
  res.json().then(parsedResponse);
}

function onPress() {
  var title = document.getElementById("title").value;
  var description = document.getElementById("description").value;

  console.log(title, "\n", description);

  fetch("http://localhost:3000/todos", {
    method: "POST",
    body: JSON.stringify({
      title: title,
      description: description
    }),
    headers: {
      "Content-Type": "application/json"
    }
  }).then(callback);
}
<body>

  Todo title
  <input type="text" id="title">
  <br><br> Todo description
  <input type="text" id="description">
  <br><br>
  <button onclick="onPress()">send todo</button>
  <div id="mainArea">
  </div>
</body>