I need to fix a bug in the code below. I would like to add list items to 'ul' element while clicking the button. Now after looping it adds the last item every time the button is clicked. And another thing, How to upload all three items "li" while clicking the button once? Thank you.
let readId = [{id: 1, name: "John"}, {id: 2, name: "James"}, {id: 3, name: "Tom"}]
let ul = document.getElementById("root");
function createItems() {
let li = document.createElement("li");
for (let i = 0; i < readId.length ; i++) {
li.setAttribute("id", readId[i].id)
li.innerHTML = readId[i].name;
ul.appendChild(li);
}
}
<button onclick="createItems()">add item</button>
<ul id="root">
</ul>
let li = document.createElement("li");into your loop