2

I have an ordered list in HTML.

<ol class="btns">
  <li>First item</li>
  <li>Second item</li>
  <!--Third one goes here-->
  <li>Four item</li>
</ol>

I want to add a new list item with js into third order. How can I do that?

Here's demo: http://jsbin.com/akahow/2/edit

More info: appendChild adds new item to end of list, I tried insertBefore but failed, only I could done with insertBefore adding it to first place. But I want to put it third place.

m59
  • 43,214
  • 14
  • 119
  • 136
Imrahil
  • 133
  • 2
  • 10

3 Answers3

2

http://jsfiddle.net/k6xVc/

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>
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
1

Your first problem is that you've used getElementsByClassName, which returns an array of nodes, even if the array only contains one node. If you are absolutely sure that there is one and only one element with that class, you should change the line to:

var findmenu = document.getElementsByClassName("btns")[0];

Then you need to use insertBefore to insert the item into the stack. However, insertBefore requires a reference to the actual object in front of which you want to insert your node, not the index. In your case, you'd add the line:

findmenu.insertBefore(paragraph,findmenu.childNodes[4]);

You may notice that we had to use the fifth index ([4]) to insert the node into the correct place. This is because the childNodes array includes all types of nodes, including Text, Elements and Comments.

Gareth Cornish
  • 4,357
  • 1
  • 19
  • 22
0

Get 2nd <li> as element and append to that by using appendChild

Check this DEMO

rahul
  • 100
  • 8