使用 vanilla JavaScript 在 </body> 标签之前插入元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14801921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:37:35  来源:igfitidea点击:

Insert element before </body> tag with vanilla JavaScript

javascript

提问by jviotti

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

我对 vanilla Javascript 不是很熟悉,一直使用 jQuery。我想这到目前为止,但得到了在中间的元素<head><body>

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

回答by dfsq

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

这很简单。使用appendChild方法,它可以写成:

document.body.appendChild(myElement);