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

121
Visualizações
How to make appended child appear above all divs just below body tag on web page
var data = "Mike, Henry, Pete";
data = data.replaceAll(" ", "");
var data_array = data.split(',');
var newArr = data_array.map(x => 'Name: ' + x);
var item = newArr[Math.floor(Math.random()*newArr.length)];

var heading = document.createElement('h1');
  heading.textContent = item;
  document.body.appendChild(heading);

The h1 appears below the other divs on the page.(appears at bottom of page) How do I get it to appear at the top, just below the opening body tag with javascript?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Solution 1

You can try using Node.insertBefore().

Try something like this:

var heading = document.createElement('h1');
heading.textContent = item;

document.body.insertBefore(heading, document.body.childNodes[0]); // This here...

Here, you're basically inserting heading element before the first childNode of <body>. This may throw, you need to make sure <body> has children so that document.body.childNodes won't be undefined, or you can just use document.body.firstChild instead of document.body.childNodes[0].

You can read more about Node.insertBefore()

Here's an example:

function insertHeading(){
  var heading = document.createElement('h1');
  heading.textContent = "I am the Missing Heading.";
  document.body.insertBefore(heading, document.body.firstChild);
}
<body>
  <p>I am a paragrapth that belongs to an article. But my heading is missing.</p>
  <p>I am a sister paragraph that belongs to a missing header.</p>

  <button onClick="insertHeading()">Insert heading</button>
</body>


Solution 2

Use Element.prepend():

The Element.prepend() method inserts a set of Node objects or string objects before the first child of the Element.

In this case document.body is your Element. You can just append the heading like this document.body.prepend(heading).

You can read more about .prepend(). But this solution lacks browser support. It's not available on IE at all.

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