Search code examples
jqueryappendchildappendto

jQuery Insert After Append?


I have the following HTML

<ul>
   <li>Some stuff first<li>
</ul>

Basically I am using appendTo(ul) to append a bunch of stuff to this but I want it to actually append AFTER the first child li ?

How can I do this ?

I've tried .appendTo(ul).insertAfter('li:first');


Solution

  • You don't need to combine appendTo and insertAfter, you can just use insertAfter and make the selector more specific:

    var li = $("<li>New</li>");
    li.insertAfter($("ul li:first"));
    

    Here's a working example.

    Edit based on comments

    I think what you mean is that you already have the ul in a variable and would like to use that. If that's the case, you could try something like this:

    var li = $("<li>New</li>");
    li.insertAfter(ul.children().eq(0));
    

    Here's an example of that one.