SLC SLC - 1 year ago 46
HTML Question

Insert item into unordered list at a given index with Jquery

I have:


<li>King Kong</li>


I want to insert
<li>Pink Panther</li>
after Godzilla (index 2). How can I do this?


You can use the after() method with the :eq() selector:

$("ul li:eq(1)").after($("<li>Pink Panther</li>"));

Note that, since :eq() is zero-based, Godzilla has index 1 instead of 2.