1

I have an array of objects like this:

const people = [
    { name: 'Bill', dob: '1949-08-11' },
    { name: 'Jill', dob: '1949-08-18' }
]

I'd like to list them inside my html document, inside a wrapper div.

This is what I tried. I'm using a for loop like this:

for (let i = 0; i < people.length; i++) {
    wrapper.innerHTML = people[i].name   
}

But this only outputs one name.

The same happens when I try it with forEach

people.forEach( person => {
    console.log(person.name)
   wrapper.innerHTML = person.name
})

The console.log lists both names, but in the html only one item is listed.

What am I doing wrong?

1
  • 4
    You are overwriting the HTML each time. Alternatively, see createElement and appendChild Commented Sep 19, 2022 at 7:39

2 Answers 2

3

You can use a variable to store it

var content = "";
for (let i = 0; i < people.length; i++) {
    content += people[i].name + " ";   
}
wrapper.innerHTML = content;

Another choice is to create element dynamiclly

const people = [
    { name: 'Bill', dob: '1949-08-11' },
    { name: 'Jill', dob: '1949-08-18' }
];

var ul = document.querySelector("#user_list");
people.forEach(p =>{
  var li = document.createElement("li");
  li.innerHTML = "name: " +p.name +"    dob: " + p.dob;
  ul.append(li);
});
<div>
  User infos:
  <ul id="user_list">
  </ul>
</div>

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

Comments

0

You are replacing the content of innerHTML on every call. you need to append the contents, something like

for (let i = 0; i < people.length; i++) {
 wrapper.innerHTML =  wrapper.innerHTML +"<br>";
    wrapper.innerHTML = wrapper.innerHTML + people[i].name  ; 
}

this should work.

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.