I'm making a simple task list that will take user input and append it to and unordered list whenever the add button is clicked. Once the item is added the text will be appended to a list element along with a delete button. I'm new to JavaScript so I don't quite know how to make the delete button remove the list element that the user clicks on. Note: it's a span element, not a button.
I think removeChild() might be good, but I can't seem to implement it.
let addButton = document.getElementById("add-item");
addButton.addEventListener("click", function () {
// Retrieves the 'list'
let list = document.getElementById("items");
let textNode = window.prompt("Enter item:");
if (textNode != null) {
let item = document.createElement("li");
//Creates a textnode from the users input
item.appendChild(document.createTextNode(textNode));
//Adds the users textnode at the end of the list
list.appendChild(item);
// Creates 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>
clickevent listener to thedeleteButtonelement and executeitem.remove()when the callback of that listener runs, eg:deleteButton.onclick = () => item.remove()