Skip to content
Advertisement

Insert element before tag with vanilla 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);

Advertisement

Answer

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

document.body.appendChild(myElement);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement