0

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>

2
  • If this is a task for college or tutorial that is fine. Otherwise use a framework like jquery, vue or angular Commented Jun 9, 2020 at 19:42
  • 1
    Move let li = document.createElement("li"); into your loop Commented Jun 9, 2020 at 19:45

3 Answers 3

1

Use a for each like this for better readability and I prefer using innerHTML property instead of createElement(), setAttribute...

let readId = [{id: 1, name: "John"}, {id: 2, name: "James"}, {id: 3, name: "Tom"}],
  ul = document.getElementById("root");

function createItems() {
  readId.forEach(function(li) {
    ul.innerHTML += `<li id="${li.id}">${li.name}</>`;
  });
}
<button onclick="createItems()">add item</button>
<ul id="root">
</ul>

Sign up to request clarification or add additional context in comments.

Comments

0

You need to create a new li element for each name.

let readId = [{id: 1, name: "John"}, {id: 2, name: "James"}, {id: 3, name: "Tom"}]
let ul = document.getElementById("root");

function createItems() {
  for (let i = 0; i < readId.length ; i++) {
    let li = document.createElement("li");
    li.setAttribute("id", readId[i].id)
    li.innerHTML = readId[i].name;
    ul.appendChild(li);
  }
}

createItems();
<ul id="root"></ul>

1 Comment

Great. Thank you!
0

You need to create 3 li nodes, so the first line in your function where you declare li must go into the for loop, on top of all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.