2

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 Answer 1

2

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>

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

1 Comment

@VedTiwari There are other ways too, but basically you need to iterate over the array. Do accept if the answer helped you

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.