84

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)?

6 Answers 6

92

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

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

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

1
  • I want to fetch an element(div) to a variable. how can i do this? Feb 25, 2016 at 13:35
27

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”.

1
  • 1
    Answers my question. "What's the opposite of append" Aug 2, 2016 at 18:59
18

Use the remove() method:

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

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();
2
  • Can you explain a bit more? Aug 2, 2018 at 10:53
  • @ShamseerAhammed What don't you understand?
    – RoToRa
    Aug 3, 2018 at 8:02
10

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...");
2
  • 1
    I believe .contents().remove() equals .empty().
    – pimvdb
    Jul 30, 2011 at 16:55
  • 2
    I'm not entirely sure whether you know of chaining - just in case yo don't, you can combine statements in jQuery like $(...).empty().append(...) :)
    – pimvdb
    Jul 30, 2011 at 20:26
5

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

Here a very good tutorial.

Not the answer you're looking for? Browse other questions tagged or ask your own question.