Perform a task for every object in an array JavaScript

Viewed 160

I have an array in JavaScript, I would like the code to display each of the items in the array in an h1 element. How do I do this?

This is my idea so far:

names = ["Jeff", "Steve", "Bill"];

function show() {
  let card = document.createElement('div');
  card.innerHTML = '<h1>${names}</h1>';
  document.body.appendChild(card);
}
<button onclick="show()">Click to show</button>

How do i have it so that each h1 element represents each value of the names array?

1 Answers

Use .forEach():

const names = ["Jeff", "Steve", "Bill"];

function show() {
  let card = document.createElement('div');
  names.forEach(name => {
    card.innerHTML += `<h1>${name}</h1>`
  });
  document.body.appendChild(card);
}
<button onclick="show()">Click to show</button>

Related