Removing an AppendTo element jQuery

5.4k Views Asked by At

I have a function that appends dynamic a and img tags to a specific div ID :

$('<a class="fap-single-track" href="http://web.com"><img src="http://web.com/image.jpg').appendTo("#status_01");

But I want the user to be able to update this link (elsewhere on the page).

How do I remove the appended data from #status_01 when I don't know exactly what the data is going to be (the url and image links are being gathered from a remote API).

The problem I'm having is that when the user selects a new URL to populate the appendTo data, the old one is also there, so I end up with multiple <a> & <img> sets.

I've tried a bunch of different ways but nothing seems to work.

If I :

$('#status_01').remove(); // before adding new data

The status_01 DIV is no longer available in the dom for the next function.

$('#status_01').detach();

Doesn't work either.

I've also tried and mixture of prepend and some other stuff but none of it seems to get rid of the appendTo data.

Is it possible?

Or maybe there is something other than appendTo that I can use instead to attach the data in the first place?

2

There are 2 best solutions below

1
Remy Grandin On BEST ANSWER

This maybe ?

$('#status_01').html("");

Or, if you want to only remove the last :

$('#status_01').children().last().remove();
1
wahwahwah On

In addition to @Remy's correct answer, you can also use .empty():

$('#status_01').empty();