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

388
Visualizações
How to insert a div as the first element in a container with JavaScript

I have created a div with Javascript, this displays correctly, however it is not in the place where I want, I would like to put it inside a container as the first element. I'm not very good, I'm trying to learn, so sorry for the triviality of the question.

How do I put the div I created inside an already existing container as the first element?

Beyond that I would like to understand the logic of the operation, for example, how can I move the new div as the last element? Or as a second element ?

This is the Js code

// Add New Element
var newEl = document.createElement("div");
var text = document.createTextNode("Hello");
   newEl.appendChild(text);
   var element = document.getElementById("main_container");
   element.appendChild(newEl);

This is what I am trying to achieve

<div id="main_container" class="something">
   <div class="new_element">Hello</div>
   <div class="item">One</div>
   <div class="item">Two</div>
   <div class="item">Three</div>
</div>

This is what I got for now

<div id="main_container" class="something">
   <div class="item">One</div>
   <div class="item">Two</div>
   <div class="item">Three</div>
</div>
<div>Hello</div>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

const parent;
const newFirstChild;
parent.insertBefore(newFirstChild, parent.firstChild);

In your case:

element.insertBefore(newEl, element.firstChild)

If you want to insert at a different index you can do it like this:

parent.insertBefore(newEl, parent.children[2])
about 4 years ago · Juan Pablo Isaza Relatório

0

This should work:

element.insertBefore(newEl, element.firstChild)
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