Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
How to create several buttons at once in pure javascript?

CSS grid layout:

.wrapper {
    display: grid;
    grid-template-areas: "btn1 btn2 btn3 btn4";
    grid-template-columns: repeat(4, 1fr);
}
#btn {grid-area: "btn1"}
#btn2 {grid-area: "btn2"}
#btn3 {grid-area: "btn3"}
#btn4 {grid-area: "btn4"}

created by div and button:

const div = document.createElement("div");
div.classList.add("wrapper");
const body = document.body;
body.appendChild(div);
const button = document.createElement("button");
button.textContent = "Click1";
button.setAttribute("id", "btn");

Next, I want to create three more buttons based on the first one and paste them into their respective areas. If you stupidly describe each action:

const b2= button.cloneNode(true);
const b3= button.cloneNode(true);
const b4= button.cloneNode(true);
b2.setAttribute('id', 'btn2');
b3.setAttribute('id', 'btn3');
b4.setAttribute('id', 'btn4');
b2.textContent = "Click"+2;
b3.textContent = "Click"+3;
b4.textContent = "Click"+4;
div.appendChild(button);
div.appendChild(b2);
div.appendChild(b3); 
div.appendChild(b4);

How to do it optimally? Something like this (doesn't work):

let b2, b3, b4;
let arr = [b2,b3,b4]
 let i=2;
     while(i<5){
     for(let j=0; j<arr.length; j++){
     arr[j].setAttribute('id', 'btn'+ i);
     arr[j].textContent= "Click"+i;
div.appendChild(arr[j])
      } i++}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Using insertAdjacentHTML simplifies the task. In this snippet the div and buttons are created in one go:

let buttons = [...Array(4)].map( (_, i) => 
  `<button id=btn${i + 1}>Click ${i + 1}</button>`);
document.body.insertAdjacentHTML(
  `beforeend`, `<div id="buttons">${
    buttons.join(``)}</div>`);
button {margin-right: 3px;}
#buttons {
  border: 1px solid #ddd;
  padding: 0.3rem;
  width: 50vw;
  text-align: center;
}

about 4 years ago · Juan Pablo Isaza Relatório

0

There's no need for the repetition, or for the clone, just a single for loop. Here using a documentFragment to avoid multiple insertions into the DOM.

const div = document.createElement('div');
div.classList.add('wrapper');

document.body.appendChild(div);

const buttonCount = 4
const buttonFragment = document.createDocumentFragment();
for (let i = 1; i <= buttonCount; i++) {
    const button = document.createElement('button');
    button.textContent = `Click${i}`;
    button.id = `btn${i}`;
    buttonFragment.append(button);
}

div.append(buttonFragment);
.wrapper {display: grid; grid-template-areas: "btn1 btn2 btn3 btn4"; grid-template-columns: repeat(4, 1fr);}

#btn1 {grid-area: "btn1"; background-color: pink;}
#btn2 {grid-area: "btn2"; background-color: aquamarine;}
#btn3 {grid-area: "btn3"; background-color: gray;}
#btn4 {grid-area: "btn4"; background-color: salmon;}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda