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

Asked

Viewed 401 times

0

I have an HTML div that displays totals of a calculation, and I need each time a new one is generated (at the click of the Generate button) a new blank div is created to receive the values, stacking the already generated ones under the other.

HTML code

BOOT

<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>
  • You want to generate only one blank div each time you click the button?

1 answer

2


To create copies of the elements you already have you can use the function cloneNode. Having the copies in hand just needs to put them in the right place, which would be the end of all the others you already have. Can do this using the function insertBefore, specifying the reference element as the parent, and indicating null as 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 may want to deepen:

  • Thank you Isac, it worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.