我有一个 HTML 格式的有序列表。
<ol class="btns">
<li>First item</li>
<li>Second item</li>
<!--Third one goes here-->
<li>Four item</li>
</ol>
我想用 js 添加一个新的列表项到第三顺序。我怎样才能做到这一点?
这里是演示:http://jsbin.com/akahow/2/edit
更多信息:appendChild
将新项目添加到列表末尾,我尝试insertBefore
但失败了,只有我可以用完成insertBefore
将其添加到第一位。但我想把它放在第三位。
最佳答案
var paragraph = document.createElement("li");
var textNode = document.createTextNode("Third item");
paragraph.appendChild(textNode);
var list=document.getElementById("jack");
list.insertBefore(paragraph,list.childNodes[4]);
HTML:
<ol class="btns" id="jack">
<li>First item</li>
<li>Second item</li>
<!--Third one goes here-->
<li>Four item</li>
</ol>
关于javascript - 如何在js中将节点 append 到首选位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14041043/