Hi Im making a list which takes the user input and places it as a list item. Each list item also gets a button which says delete. This button should delete the list item and the button. I have managed to do this however when i press the delete button it is not deleting the corresponding list item. It is deleting the first "li" . Can anyone help me to fathom out how I get the delete button to delete the corresponding "li" and not the first one in the list.
const unorderedList = document.getElementById("unorderedList");
const input = document.getElementById("item");
const addToPage = document.getElementById('addButton').onclick = function () {
userInput = document.getElementById("item").value;
let newDiv = document.createElement("div");
newDiv.className = "newDiv";
newDiv.id = "newDiv";
let newButton = document.createElement("button");
newButton.innerText = "Delete";
newButton.className = "newButton";
newButton.id = "newButton";
newButton.onclick = removeItem;
const newListItem = document.createElement("li");
newListItem.innerText = userInput;
newListItem.className = "listItem";
newListItem.id = "listItem";
newDiv.appendChild(newListItem);
newDiv.appendChild(newButton);
unorderedList.appendChild(newDiv);
};
}
li {
margin-bottom: 10px;
}
li button {
font-size: 12px;
margin-left: 20px;
color: #666;
}
<h1>My shopping list</h1>
<div>
<label for="item">Enter a new item:</label>
<input type="text" name="item" id="item">
<button id="addButton">Add item</button>
</div>
<ul id="unorderedList">
</ul>
2
Answers
To remove the item where the Delete button was pressed, you can simply rely on the
event.target
(being the clicked button) and then traverse the DOM by selecting its closest parent having thenewDiv
class so you can delete the whole element.https://developer.mozilla.org/en-US/docs/Web/API/Event/target
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
https://developer.mozilla.org/en-US/docs/Web/API/Element/remove
You have invalid HTML by adding same id everytime (I commented it). Your removeItem() function is also not defined. I added a function removeMe and event listener that checks for click that matches the delete button to call the removeMe function.