SLC SLC - 5 months ago 7x
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.