[英]How to append an element before another using Javascript?
I tried following the a wiki and looking into multiple questions here but I still have problems with insertBefore.. 我尝试遵循wiki,并在这里调查了多个问题,但是insertBefore仍然有问题。
This is my sample: 这是我的示例:
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
<script>
topbar = document.getElementsById("container");
boardlist = document.getElementsById("first");
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML("0");
topbar.inserBefore(bmcontainer, boardlist);
</script>
I want to append the span#zero before the span#first. 我想在span#first之前附加span#zero。 What am I doing wrong? 我究竟做错了什么? I'm trying to not use jQuery, so I'm looking for a totally javascript solution. 我试图不使用jQuery,所以我正在寻找一种完全JavaScript的解决方案。
Prepend pure javascript 前置纯JavaScript
MDN article on insertBefore() 有关insertBefore()的MDN文章
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
Source: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/#Prepend 来源: http : //clubmate.fi/append-and-prepend-elements-with-pure-javascript/#Prepend
Also, the jQuery prepend() Method 另外,jQuery prepend()方法
Node.insertBefore()
is the answer. Node.insertBefore()
是答案。
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
If you have Parent Node
, then you should use ParentNode.prepend()
如果您有Parent Node
,那么您应该使用ParentNode.prepend()
ParentNode.prepend(nodesToPrepend);
Take a look @ mentioned links for full documentation and examples. 查看@提到的链接以获取完整的文档和示例。
Update 更新资料
You have some issues in your code ( typo and wrong usage of innerHTML
), here is fixed code. 您的代码中有一些问题( innerHTML
错字和错误用法 ),这是固定的代码。
HTML 的HTML
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
JS JS
var topbar = document.getElementById("container"),
boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML = "0"; // innerHTML is not a function, it's a property
topbar.insertBefore(bmcontainer, boardlist);
Notice that InnerHTML
is not a function
, it's a property
, read more about that here: Element.innerHTML 注意, InnerHTML
不是一个function
,它是一个property
,有关更多信息,请参见 : Element.innerHTML
You can use the insertAdjacentElement function. 您可以使用insertAdjacentElement函数。
var boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
boardlist.insertAdjacentElement('beforebegin', bmcontainer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.