How to insert a new div and stack them after clicking a button

0

I have an HTML div that displays totals of a calculation, and I need every new one (on the click of the Generate button) to generate a new blank div to get the values, stacking those already generated one under the other.

HTML Code

BOTAO

<input type="button" value="Gerar Lote" />

HTML

<div class="l1">
    <h4>Resumo</h4>
</div>

<div class="l25">
    <label>Débitos</label>
    <input value="0.00" />
</div>

<div class="l25">
    <label>Créditos</label>
    <input value="0.00" />
</div>
    
asked by anonymous 09.04.2018 / 22:40

1 answer

2

To create copies of the elements you already have, you can use cloneNode . Having the copies in hand just needs to put them in the right place, which would be at the end of all the others you already have. You can do this by using the insertBefore function, specifying the reference element as the parent, and indicating null as the reference node.

Example:

const resumo = document.querySelector(".l1");
const [debitos, creditos] = [...document.querySelectorAll(".l25")];

//definir o código para o evento de click no botão gerar
document.getElementById("gerar").addEventListener("click", () => {

  //clonar os 3 divs
  const novoResumo = resumo.cloneNode(true); //true indica cópia profunda
  const novoDebito = debitos.cloneNode(true);
  const novoCredito = creditos.cloneNode(true);
  
  //inserir no fim por ordem cada um dos divs clonados
  resumo.parentNode.insertBefore(novoResumo, null);
  resumo.parentNode.insertBefore(novoDebito, null);
  resumo.parentNode.insertBefore(novoCredito, null);
});
<!-- adicionei o id gerar para ficar mais simples -->
<input id="gerar" type="button" value="Gerar Lote" />

<div class="l1">
    <h4>Resumo</h4>
</div>

<div class="l25">
    <label>Débitos</label>
    <input value="0.00" />
</div>

<div class="l25">
    <label>Créditos</label>
    <input value="0.00" />
</div>

Used features you might want to dig deeper:

09.04.2018 / 23:26