Basically I’m creating a to do list, where i created a bunch of li elements which is push into an array.
Then when I want to loop through the array and add event listener, it couldn’t work.
After checking it was because the array i declared was still considered empty even after I inputted the list.
Any help?
Code:
// Declaration of variables
let input = document.querySelector(".input")
let button = document.querySelector("button")
let list = document.querySelector(".list")
let itemArray = []
//Functions
const createList = () => {
//Create newItem to create a li element, before attaching content and it to div
let newItem = document.createElement("LI")
newItem.appendChild(document.createTextNode(input.value))
//Create a button to remove and attach it to newItem, after attaching the classes
let remove = document.createElement("BUTTON")
remove.appendChild(document.createTextNode("X"))
remove.classList.add("remove-button-styling")
newItem.appendChild(remove)
//Create a div and adding the respective class
let div = document.createElement("DIV")
div.classList.add("list-div")
//Attaching newItem to the div
div.appendChild(newItem)
//Attaching the div to the list
list.appendChild(div)
//Push the item we created, along with the div to an array
itemArray.push(div)
input.value = ''
}
const keypressInput = (event) => {
if (event.keyCode === 13) {
createList()
}
}
// Event listener
button.addEventListener("click", function () {
createList()
})
input.addEventListener("keypress", keypressInput)
// list.addEventListener("click", function () {
// alert()
// })
})