Opposite of append in jQuery

JavascriptJquery

Javascript Problem Overview


I use .append to add to a div

$(this).append('<ul><li>test</li></ul>');

how can I search for a <ul> and remove it if it exists in the children of $(this)?

Javascript Solutions


Solution 1 - Javascript

You could use remove(). More information on jQuery remove().

$(this).children("ul").remove();

Note that this will remove all ul elements that are children.

Solution 2 - Javascript

The opposite of .append() is .prepend().

From the jQuery documentation for prepend…

> The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).

I realize this doesn’t answer the OP’s specific case. But it does answer the question heading. :) And it’s the first hit on Google for “jquery opposite append”.

Solution 3 - Javascript

Use the remove() method:

$(this).children("ul").remove();

Solution 4 - Javascript

What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:

   var newUL = $('<ul><li>test</li></ul>');
   $(this).append(newUL);
 
   // Later ...

   newUL.remove();

Solution 5 - Javascript

just had the same problem and ive come across this - which actually does the trick for me:

// $("#the_div").contents().remove();
// or short: 
$("#the_div").empty();
$("#the_div").append("HTML goes in here...");

Solution 6 - Javascript

Opposite up is children(), but opposite in position is prepend().

Here a very good tutorial.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsamiView Question on Stackoverflow
Solution 1 - JavascriptJosh KView Answer on Stackoverflow
Solution 2 - JavascriptelbowlobstercowstandView Answer on Stackoverflow
Solution 3 - JavascriptFrédéric HamidiView Answer on Stackoverflow
Solution 4 - JavascriptRoToRaView Answer on Stackoverflow
Solution 5 - JavascriptMartin WirthView Answer on Stackoverflow
Solution 6 - JavascriptwarmthView Answer on Stackoverflow