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 dynamically generated list element along with a delete button. It can add and and delete items just fine as long as the text is different. The issue is whenever multiple items with the same text are generated the list won't delete the specific item clicked, it will start from the bottom of the list and work its way up. How could I fix this issue?
const container = document.querySelector(".container");
const addButton = document.querySelector(".btn");
const userInput = document.querySelector(".input");
const ul = document.createElement("ul");
addButton.addEventListener("click", addTask)
function addTask() {
const li = document.createElement("li");
li.className = "task";
li.innerHTML = `
<div class="note-container">
<p>${userInput.value}</p>
</div>
`
const deleteButton = document.createElement("button");
deleteButton.classList.add("delete-btn");
deleteButton.innerHTML = "Delete Task";
li.append(deleteButton);
ul.append(li);
container.append(ul);
deleteButton.addEventListener("click", deleteTask)
}
function deleteTask(e) {
let item = e.target.parentNode;
item.addEventListener("click", () => {
item.remove();
})
}
ul {
list-style: none;
margin-top: 1rem;
}
.note-container {
display: inline;
}
li {
display: flex;
justify-content: space-between;
}
button {
display: inline;
}
#button {
background-color: #2e8bc0;
border: none;
}
#button:focus {
outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" integrity="sha512-EZLkOqwILORob+p0BXZc+Vm3RgJBOe1Iq/0fiI7r/wJgzOFZMlsqTa29UEl6v6U6gsV4uIpsNZoV32YZqrCRCQ==" crossorigin="anonymous" />
<link rel="stylesheet" href="styles.css">
<title>Todo List</title>
</head>
<body>
<div class="container">
<h1>Todo List</h1>
<label for="">Task</label>
<input type="text" name="" id="" class="u-full-width input">
<button class="button-primary btn u-full-width" id="button">Add Task</button>
</div>
<script src="app2.js"></script>
</body>
</html>