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: 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.
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.
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With