I am in the process of creating a basic task list that allows users to input tasks. When the add button is clicked, the task will be added to an unordered list along with a delete button. As a beginner in JavaScript, I am struggling to figure out how to make the delete button remove the specific list element when clicked (it's a span element, not a button).
Although I believe removeChild() could be useful for this task, I am having difficulty implementing it.
let addButton = document.getElementById("add-item");
addButton.addEventListener("click", function () {
// Get the 'list'
let list = document.getElementById("items");
let textNode = window.prompt("Enter item:");
if (textNode != null) {
let item = document.createElement("li");
// Convert user input into a textnode
item.appendChild(document.createTextNode(textNode));
// Append user's textnode at the end of the list
list.appendChild(item);
// Create a delete button
let deleteButton = document.createElement("span");
deleteButton.innerHTML = "Delete"
item.appendChild(deleteButton)
}
});
ul {
padding: 0px;
}
li {
display: flex;
background-color: #eee;
margin: 5px;
padding: 5px;
align-items: center;
}
li > span {
margin-left: auto;
background-color: #aaa;
padding: 5px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="app_2.css" rel="stylesheet>
<title>Items</title>
</head>
<body>
<h1>Items</h1>
<ul id="items">
<!--
This is the template for an item in the list:
<li>The first item is free! <span>Delete</span></li>
-->
</ul>
<button type="button" id="add-item">Add item</button>
<script src="app_2.js"></script>
</body>
</html>