I'm new to JavaScript and I have made a list. You can add new items inn the list, you can delete the items from the list, also it has a little css for text decoration.
And I have a problem, I can't delete the new items from the list, I can only delete the old items from the list. If a add a new item, I can't delete it
This is the code:
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var liEl = document.getElementsByTagName("li");
var btn = document.querySelectorAll("button");
var btnLength = btn.length;
function inputLength() {
return input.value.length;
}
function createListElement() {
var li = document.createElement("li");
var delBtn = document.createElement("button");
li.appendChild(document.createTextNode(input.value + " "));
delBtn.appendChild(document.createTextNode("Delete"));
ul.appendChild(li);
li.appendChild(delBtn);
btnLength++;
btn[btnLength].addEventListener("click", clearItem);
input.value = "";
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeypress(theEvent) {
if (inputLength() > 0 && theEvent.keyCode === 13) {
createListElement();
}
}
function changeClass() {
this.classList.toggle("done");
}
function clearItem() {
this.parentNode.remove();
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
eventChangeClass();
eventClearItem();
function eventChangeClass() {
for (var i = 0; i < liEl.length; i++) {
liEl[i].addEventListener("click", changeClass);
}
}
function eventClearItem() {
for (var i = 1; i < btnLength; i++) {
btn[i].addEventListener("click", clearItem);
}
}
.done {
text-decoration: line-through;
}
<!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>Delete</button></li>
<li>Jello <button>Delete</button></li>
<li>Spinach <button>Delete</button></li>
<li>Rice <button>Delete</button></li>
<li>Birthday Cake <button>Delete</button></li>
<li>Candles <button>Delete</button></li>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
This is the error:
Uncaught TypeError: Cannot read property 'addEventListener' of undefined
at createListElement (script.js:20)
at HTMLButtonElement.addListAfterClick (script.js:26)
querySelectorAllis not a live collection of allbuttons. Quick fix might be to usegetElementsByTagNameinstead, which is a live collection, but it would be even better to use event delegation instead.btn[btnLength]will always be undefined even with a live collection as there is no element at btnLength.