Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!