jQuery insertAt
Try something like this:
$("#thelist li").eq(3).after("<li>A new item</li>");
With the eq
function, you can get a specific index of the elements retrieved...then, insert the new list item after it.
In the above function, I am inserting a new item at position 4 (index 3).
More info about the function at the jQuery Docs
A simple jQuery plugin (a small test suite) which permits adding an item at any index including 0.
$.fn.insertAt = function(index, $parent) { return this.each(function() { if (index === 0) { $parent.prepend(this); } else { $parent.children().eq(index - 1).after(this); } });}
Assuming we have the following HTML:
<ul id="items"> <li>A</li></ul>
Then inserting an item at index 0 $('<li>C</li>').insertAt(0, $('#items'))
will result in
<ul id="items"> <li>C</li> <li>A</li></ul>
Inserting another item, this time at index 1 $('<li>B</li>').insertAt(1, $('#items'))
yields
<ul id="items"> <li>C</li> <li>B</li> <li>A</li></ul>
Disclaimer: there is no error handling of input parameters. If index
is negative or greater than the length of children or if index
is not a number the behavior is more or less undefined. If $parent
is not a jQuery object insertAt
will fail.
Similar to Dreas's answer, but slightly different and possibly more efficient:
$("#thelist li:eq(2)").after("<li>new item</li>");
Or another way:
$("<li>new item</li>").insertAfter("#thelist li:eq(2)");