I don’t know what is wrong with this code. When I append app child to the tag and when I try to click the delete button of the appended child it shows me this error.
if you have a solution then provide me or give me suggestion to do this task
Cannot read properties of undefined (reading ‘remove’).
You can check the code as well.
HTML Code.
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items" />
<button id="enter">Enter</button>
<ul>
<li class="bold red" random="23">
Notebook <button class="deleteButton">Delete</button>
</li>
<li>Jello <button class="deleteButton">Delete</button></li>
<li>Spinach <button class="deleteButton">Delete</button></li>
<li>Rice <button class="deleteButton">Delete</button></li>
<li>Birthday Cake <button class="deleteButton">Delete</button></li>
<li>Candles <button class="deleteButton">Delete</button></li>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript Code.
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.querySelector("li");
var deleteButton = document.getElementsByClassName("deleteButton");
var liAll = document.querySelectorAll("li");
function inputLength() {
return input.value.length;
}
function createListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
const returnedLi = createDeleteButtonElement(li);
ul.appendChild(returnedLi);
input.value = "";
strikeThroughOnClick();
deleteOnClick();
}
function createDeleteButtonElement(li) {
var button = document.createElement("button");
button.appendChild(document.createTextNode("Delete"));
button.classList.add("deleteButton");
li.appendChild(button);
return li;
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeypress(event) {
if (inputLength() > 0 && event.keyCode === 13) {
createListElement();
}
}
function strikeThrough(i) {
liAll[i].classList.contains("done")
? liAll[i].classList.remove("done")
: liAll[i].classList.add("done");
}
function deleteItem(i) {
// console.log();
liAll[i].remove();
// this.parentNode.remove();
}
function deleteOnClick() {
for (let i = 0; i < deleteButton.length; i++) {
deleteButton[i].addEventListener("click", () => deleteItem(i));
}
return deleteButton;
}
function strikeThroughOnClick() {
for (let i = 0; i < liAll.length; i++) {
liAll[i].addEventListener("click", () => strikeThrough(i));
}
return liAll;
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
strikeThroughOnClick();
deleteOnClick();