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.
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.
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
Try to use this method.. it's the simplest way to insert text inside an element..
<div id="test"></div>
$('#test').append();
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)");