Javascript 如何在body标签中插入Before()元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6013861/
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
How to insertBefore() element in body tag?
提问by slemdx
I am trying to use insertBefore in js like this:
我正在尝试在 js 中使用 insertBefore,如下所示:
var p = document.createElement("p");
p.innerHTML = "test1";
document.body.insertBefore(p, null);
var p = document.createElement("p");
p.innerHTML = "test2";
document.body.insertBefore(p, null);
But that would add the last p element just before the close of the body tag, how could I use it so it will be added to the top when it opens? So the last element added will be the first element inside the body tag.
但这会在 body 标签关闭之前添加最后一个 p 元素,我如何使用它以便在打开时将其添加到顶部?所以添加的最后一个元素将是 body 标签内的第一个元素。
I tried:
我试过:
document.body.insertBefore(p, document.getElementsByTagName('body')[0]);
But firebug shows:
但萤火虫显示:
Node was not found" code: "8
未找到节点”代码:“8
回答by alex
You can get the first child of the body
element with the firstChild
property. Then use it as the reference.
您可以body
使用该firstChild
属性获取元素的第一个子元素。然后将其用作参考。
const p = document.createElement("p");
p.textContent = "test1";
document.body.insertBefore(p, document.body.firstChild);
I modernized your code for reasons :)
我出于某些原因对您的代码进行了现代化:)
回答by Gibolt
document.body.prepend(p);
This is a new addition in (likely) ES7. It is vanilla JS and is more readable than previous options. It is currently available in 94% of browsers, including Chrome, FF, and Opera.
这是(可能)ES7 中的新增功能。它是 vanilla JS,比以前的选项更具可读性。它目前在94% 的浏览器中可用,包括 Chrome、FF 和 Opera。
You can directly prepend strings, although they won't be 'p' tags
您可以直接添加字符串,尽管它们不会是 'p' 标签
document.body.prepend('This text!');
Links: developer.mozilla.org- Polyfill
回答by KooiInc
You have to insert before something. document.getElementsByTagName('body')[0]
isthe body element (the syntax is a bit of a trick to get the body element in all browsers)1. If you want to insert into the body, you want to insert before the first element of it. That could look like this:
你必须在某些东西之前插入。document.getElementsByTagName('body')[0]
是body 元素(在所有浏览器中获取 body 元素的语法有点小技巧)1. 如果要插入到正文中,则要在它的第一个元素之前插入。看起来像这样:
var body = document.body || document.getElementsByTagName('body')[0],
newpar = document.createElement('p');
newpar.innerHTML = 'Man, someone just created me!';
body.insertBefore(newpar,body.childNodes[0]);
1in some browsers it's document.body
, other document.documentElement
etc., but in all browsers the tagname is body
1在某些浏览器中它是document.body
,其他document.documentElement
等等,但在所有浏览器中标记名是body