SLC SLC - 6 months ago 11
HTML Question

Insert item into unordered list at a given index with Jquery

I have:

<ul>

<li>Cthulhu</li>
<li>Godzilla</li>
<li>King Kong</li>

</ul>


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

Answer

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.

Comments