How do I make an h1 element for each value in an array?

Viewed 457

I have an array in JavaScript as shown in the example below. My question is: how can I have an h1 element for each value of the array when a button is clicked?

Names = []

function submit() {
  let inputValue = document.getElementById("name").value;
  Names.push(inputValue);
  let frame = document.getElementById("frame");
  frame.innerHTML = `<div><h1>${Names}</h1></div>`
  
}
<button onclick="submit()">Submit</button>
<input placeholder="name" id="name">
<div id="frame"></div>

How do I create separate H1 elements which contain each value from the array?

2 Answers

You can do it like below, by emptying the frame innerHTML every time you wish to add a new one and then iterating through the Names list and creating new h1 elements using document.createElement("h1"). The key here is to use append() to add the created element to the desired element.

Check below:

var Names = []

function submit() {
  let inputValue = document.getElementById("name").value;
  Names.push(inputValue);
  let frame = document.getElementById("frame");
  
  frame.innerHTML = "";
  
  Names.forEach(function(el, i) {
    let h1 = document.createElement("h1");
    h1.innerHTML = Names[i];
    frame.append(h1);
  });
}
<button onclick="submit()">Submit</button>
<input placeholder="name" id="name">
<div id="frame"></div>

Another, and possibly better approach would be to just use append() to add the new input, like this:

var Names = []

function submit() {
  let inputValue = document.getElementById("name").value;
  Names.push(inputValue);
  let frame = document.getElementById("frame");
  let h1 = document.createElement("h1");
  h1.innerHTML = inputValue;
  frame.append(h1);
}
<button onclick="submit()">Submit</button>
<input placeholder="name" id="name">
<div id="frame"></div>

I think you mean whenever the user enter a name and press submit.. the name should be added to a list with id frame right?

If yes then you just need to fix alittle problem:

 frame.innerHTML = `<div><h1>${Names}</h1></div>`

this line of code is causing this issue, you are rewriting the new name on top of the old one, and what you should do is something like:

frame = old frame + new name

in code :

 frame.innerHTML += `<div><h1>${Names}</h1></div>`

or

 frame.innerHTML = frame.innerHTML+ `<div><h1>${Names}</h1></div>`

both lines of codes do the same thing but are written in a different way

Related