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?
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.