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?


// Declaration of variables
let input = document.querySelector(".input")
let button = document.querySelector("button")
let list = document.querySelector(".list")
let itemArray = []

const createList = () => {
  //Create newItem to create a li element, before attaching content and it to div
  let newItem = document.createElement("LI")
  //Create a button to remove and attach it to newItem, after attaching the classes
  let remove = document.createElement("BUTTON")
  //Create a div and adding the respective class
  let div = document.createElement("DIV")
  //Attaching newItem to the div
  //Attaching the div to the list
  //Push the item we created, along with the div to an array

  input.value = ''

const keypressInput = (event) => {
  if (event.keyCode === 13) {

// Event listener
button.addEventListener("click", function () {

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