Javascript – Insert element before tag with vanilla JavaScript

javascript

<html>
  ...
  <body>
    ...
  // element should be inserted here
  </body>
</html>

I'm not very familiar with vanilla Javascript, always have worked with jQuery. I tried this so far, but that got the element in the middle of <head> and <body>.

var bodyTag = document.getElementsByTagName('body')[0];
bodyTag.parentNode.insertBefore(myElement, bodyTag);

Best Answer

It's pretty simple. Using appendChild method it can be written as short as:

document.body.appendChild(myElement);
Related Topic