A very weird paradox

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()
// })


})

Check event delegation: https://dmitripavlutin.com/javascript-event-delegation/

I’m not sure I get it, I can’t see any loops in your code. Your createList function looks more like a createListItem function (because you create only one item with it).

Does that function work, meaning that does a new list item appear? It would be easier to debug if you had a codepen or jsfiddle or similar.

I’m going to make a codepen tomorrow. I will loop but the problem is that, when despite pushing the list into the arrays already, when I check, it still considers the array empty.

let itemArray = []

I declared an itemArray, then I push some div elements into it. I was going to loop through the itemArray, but it says that is undefined. So I realize that despite pushing the div into the array, it is still considered undefined.

It’s kind of hard to explain with word, so I will put a codepen tomorrow. Thanks for repsonding

Will check first, thanks

Hey guys, I solve the paradox. DevEd video tutorial suggested using event parameters, which I had never used or recognized how useful it until now. Thanks for taking the time to respond folks