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

290
Visualizações
Unable to create div inside a div by click on a button

What I

function creatediv(){
            const creatediv = document.createElement('div');
            creatediv.innerHTML ="ADDED!";

            document.getElementsByClassName("box1").appendChild(creatediv);
        }
<div class="box1"></div>
<button class="creatediv" onclick="creatediv()">
   <i class="fa-solid fa-plus fa-xl"></i>
</button>

want to do is create a div with text ADDED! inside the div ofclass="box1" , it work with id instead class, how to do that with class, Thank you

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In case you are looking for an explanation as to why your specific code snippet is not working: getElementsByClassName returns an array. You need to refer to it with index [0]

Refer working snippet below:

function creatediv() {
  const creatediv = document.createElement('div');
  creatediv.innerHTML = "ADDED!";

  document.getElementsByClassName("box1")[0].appendChild(creatediv);
}
<div class="box1"></div>
<button class="creatediv" onclick="creatediv()">
   Add<i class="fa-solid fa-plus fa-xl"></i>
</button>

over 4 years ago · Santiago Trujillo Relatório

0

It's because you are using class instead of ID, id is a unique Identifier, so every time to get an Element by its id you always refer to the One element On the page. instead, if you get Element by Class name because multi-element can have that class you always must deal with an array of DOM Element

over 4 years ago · Santiago Trujillo Relatório

0

document.getElementsByClassName return HTMLCollection

HtmlCollection is array of Element

document.getElementById return Element

function creatediv() {
  const creatediv = document.createElement('div');
  creatediv.innerHTML = "ADDED!";

  document.getElementById("box1").appendChild(creatediv);
}
<div id="box1"></div>
<button class="creatediv" onclick="creatediv()">
   <i class="fa-solid fa-plus fa-xl"></i>
</button>

over 4 years ago · Santiago Trujillo 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