Recently, I've created a simple script that dynamically adds "li" elements to a "ul" and assigns them a specific class. However, I now want to modify the class of an "li" item when a click event occurs.
Here's the HTML structure:
<form class="form">
<input id="newInput" type="text" placeholder="Add item">
<button id="createNew" type="button">Add</button>
</form>
<h2>My List:</h2>
<div class="listBg">
<ul id="list">
</ul>
</div>
<button id="deleteAll" type="button">Clear All</button>
And here's the corresponding JavaScript code:
function addItem() {
var myList = document.getElementById("list");
var newListItem = document.createElement("li");
var itemText = document.getElementById("newInput").value;
var listText = document.createTextNode(itemText);
newListItem.appendChild(listText);
if (itemText === "") {
alert("Field cannot be empty");
} else {
var x = document.createElement("span");
x.innerText = "X";
x.className = "closer";
myList.appendChild(newListItem);
newListItem.className = "item";
newListItem.appendChild(x);
var itemText = document.getElementById("newInput");
itemText.value = "";
}
};
function itemDone() {
var listItems = document.querySelectorAll("li");
for (var i = 0; i < listItems.length; i++) {
listItems[i].classList.add("itemDone");
}
};
var items = document.getElementsByClassName("item");
for (var j = 0; j < items.length; j++) {
items[j].addEventListener("click", itemDone);
}
I'm still learning JavaScript, so any additional tips or explanations would be greatly appreciated!