Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert item into unordered list at a given index with Jquery

Tags:

html

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?

like image 290
NibblyPig Avatar asked Feb 28 '11 11:02

NibblyPig


People also ask

How can add Li in UL dynamically using jQuery?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.

Which method would you use to add one new item Li item in the beginning of ordered list?

Using jQuery With jQuery, you can create a new <li> element and add it to an existing <ol> or <ul> element using the . append() or the . prepend() method.


2 Answers

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.

like image 157
Frédéric Hamidi Avatar answered Nov 15 '22 21:11

Frédéric Hamidi


You can use eq and after like this:

$('#ul_id li:eq(1)').after('<li>Pink Panther</li>');

For eq index starts from 0 so 1 corresponds to <li>Godzilla</li>.

like image 33
Sarfraz Avatar answered Nov 15 '22 20:11

Sarfraz