Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert element before </body> tag with vanilla JavaScript

Tags:

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);
like image 929
jviotti Avatar asked Feb 10 '13 19:02

jviotti


1 Answers

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

document.body.appendChild(myElement);
like image 109
dfsq Avatar answered Oct 03 '22 20:10

dfsq