Insert item into unordered list at a given index with Jquery
I have:
开发者_C百科<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?
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>
.
$('ul').eq(1).after($('<li>Pink Panther</li'));
btw index of Godzilla is 1 since indexing starts with 0 :)
You can access the array of LIs via jquery selectors like this:
var secondElement = $("ul li")[1];
$(secondElement).after("<li>New element!</li>");
This will produce the following HTML:
<ul>
<li>Cthulhu</li>
<li>Godzilla</li>
<li>New element!</li>
<li>King Kong</li>
</ul>
you can use nth child selector
here is an example
精彩评论