tags:

views:

426

answers:

3
+1  Q: 

jQuery insertAt

I'm trying to insert an li element into a specific index on a ul element, using jQuery?

I only seem to be able to insert an element on the end of the list. I am very new to jQuery, so I may just not be thinking properly.

+7  A: 

Try something like this:

$("#thelist li").eq(2).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.

More info about the function at the jQuery Docs

Andreas Grech
Hey you changed your name! (sorry I just noticed ^^)
Pim Jager
hehe yup, I added my surname to my name =)
Andreas Grech
A: 

Try to use this method.. it's the simplest way to insert text inside an element..

<div id="test"></div>

$('#test').append();
Aristotle Ucab
+3  A: 

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)");
nickf