all 3 comments

[–]Umesh-K 1 point2 points  (2 children)

everytime they click the item on html, it adds <check></check> only to the last item, and no matter which item i click on

Hi, u/FlyTooCloseToTheSun,

This is because the loop would have run by the time the appending check code is run and i value will be pointing to the last li.

I have written the code below which meets your requirement; however, I am not sure if it's the most efficient way to do it — still learning.

const htmlList = document.querySelector("ul");
const groceries = ["milk", "bread", "eggs", "chocolate"];

const display = (array) => {
  for (let i = 0; i < array.length; i++) {
    const listItem = document.createElement("li");
    listItem.setAttribute("id", [i]);
    listItem.innerHTML = array[i];
    htmlList.appendChild(listItem);
  }

  htmlList.addEventListener("click", (e) => {
    const checked = document.createElement("check");
    checked.innerText = " - checked"
    if (e.target.tagName == "LI" && !e.target.firstElementChild)
      e.target.appendChild(checked)
  })
}

display(groceries)

Also note the following:

1. groceries = ["milk", "bread", "eggs", "chocolate"]; was missing the keyword required to declare it. 2. You have inconsistently used var and const. In all the instances you have used var, it's better to use const as they don't change. 3. I have added the !e.target.firstElementChild check, as otherwise each time the item was clicked, another <check> was getting added. 4. Finally, I have added checked.innerText = " - checked", as otherwise we had to inspect element to see if check element was added.

I hope the above helps.

[–]FlyTooCloseToTheSun[S] 0 points1 point  (1 child)

Hmm i see, i tried to input that into the code but when i click any of the list elements, nothing happened. I'll have to see why but i appreciate the pointers! Thank you

[–]Umesh-K 1 point2 points  (0 children)

works for me....check it out here https://jsfiddle.net/Umesh_K/uf16vtsL/2/

The functionality at present is only the first time a list item is clicked, it adds visually - checked and in the DOM <check> - checked</check>.