[Solved] Add and Delete Task in HTML with DOM and JavaScript

  

3
Topic starter

Extend the previous problem to display a [Delete] link after each list item. Clicking it, should delete the item with no confirmation.

Input/Output:
There will be no input/output, your program should instead modify the DOM of the given HTML document.

Sample HTML:

<h1>List of Items</h1>
<ul id="items"></ul>
<input type="text" id="newText" />
<input type="button" value="Add"
  onclick="addItem()">
<script>
  function addItem() { ...
    function deleteItem() { ... }
  }
</script>

Examples:

add delete javascript task

1 Answer
2

Here is my solution:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>List of Items:</h1>
<ul id="items"></ul>
<input type="text" id="newText">
<input type="button" value="Add New Text" onclick="addItem()">
 
<script>
    function addItem() {
        let input = document.getElementById("newText");
        let text = input.value;
        let newLi = document.createElement("li");
        newLi.textContent = text + " ";
        let deleteLink = document.createElement("a");
        deleteLink.textContent = "[Delete]";
        deleteLink.href = "#";
        deleteLink.addEventListener("click", deleteItem);
        newLi.appendChild(deleteLink);
 
        document.getElementById("items").appendChild(newLi);
        input.value = "";
 
        function deleteItem() {
            document.getElementById("items").removeChild(newLi);
        }
    }
</script>
</body>
</html>

Another function:

function addItem() {
   let text = document.getElementById("newText").value;
   let li = document.createElement("li");
   li.textContent = text;
    
   let span = document.createElement("span");
   span.innerHTML = " <a href = '#'>[Delete]</a>";
   span.addEventListener("click", function () {
       let li = span.parentNode;
       li.parentNode.removeChild(li);
   });
   li.appendChild(span);
    
    
   let items = document.getElementById("items");
   items.appendChild(li);
    
   document.getElementById("newText").value = "";
}
Share: