Dr Bracewell
Dr Bracewell

Reputation: 116

Appending new inputs with JS wipes previous ones

So I have this code,

spellNumber = 0

function createSpell() {
  document.getElementById("spells").innerHTML +=
    '<p><input type="text"></p><br />'
  spellNumber += 1;
  spellsActive = true
}
<a onClick="createSpell()" class="spellButton" style="background-color:#717171">Add a Spell</a>
<div id="spells"></div>

but whenever I try to add another input by clicking the button, it wipes any previous ones. How can I stop this from happening?

Upvotes: 0

Views: 67

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

Concatenating with existing .innerHTML will mean that only the HTML string of previous elements is retained - your inputs don't have a .value attribute, so it appears that the values get lost. (what's actually happening is that the element gets destroyed, then re-created with the new full HTML string.)

Instead of concatenating with the existing innerHTML, use createElement instead, so as not to corrupt what exists in the container already:

let spellNumber = 0;
const spells = document.getElementById("spells")

function createSpell() {
  const p = spells.appendChild(document.createElement('p'));
  const input  = p.appendChild(document.createElement('input'));
  spells.appendChild(document.createElement('br'));
  spellNumber += 1;
  spellsActive = true
}
<a onClick="createSpell()" class="spellButton" style="background-color:#717171">Add a Spell</a>
<div id="spells"></div>

Another option would be to use insertAdjacentHTML, which, like appendChild, will not corrupt existing elements:

let spellNumber = 0;
const spells = document.getElementById("spells")

function createSpell() {
  spells.insertAdjacentHTML('beforeend', '<p><input type="text"></input></p></br>');
  spellNumber += 1;
  spellsActive = true
}
<a onClick="createSpell()" class="spellButton" style="background-color:#717171">Add a Spell</a>
<div id="spells"></div>

Upvotes: 1

Related Questions