Jquery – How to use JQuery “after” selector


I can't seem to figure out a good way to do this, but it seems like it should be simple. I have an element that I want to append a div to. Then I have another element that I want to clone and shove into that intermediate div. Here's what I was hoping to do:

$("#somediv > ul").after("<div id='xxx'></div>").append($("#someotherdiv").clone());

This seems to be close, but not quite there. The problem with this is that the "append" seems to be operating on the original #somediv > ul selector. This sort of makes sense, but it's not what I wanted. How can I most efficiently select that intermediate div that I added with the after and put my #someotherdiv into it?

Best Solution

Go the other way around and use insertAfter().

$("<div id='xxx'></div>")
    .insertAfter("#somediv > ul")

Try to add your generated DOM nodes to the document only after finishing your work.

Once the nodes are added to the displayed document, the browser starts listening to any change to refresh the view. Doing all the work before adding the nodes to the displayed document does improve browser performance.