Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing appended html using jQuery?

Using jquery, I currently append html to a div on a click event. The following code allows me to fade in only the appended portion of the div:

var html = "..";
$('<div></div>').appendTo("#id").hide().append(html).fadeIn('slow');

This portion works perfectly. But how can I later remove (fade out) only the appended portion? I tried hacking this by storing the html prior to the appending, and then simply hiding everything and showing the stored html. But this does not work well when the same procedure is reused for several divs on the same page (and this seems like poor implementation). Is there a good way to do this?

Just to give an idea of why I need this: Think of a blog type page where for every article on the page there are several comments with only x amount showing by default: the click event fetches the remaining comments and displays them, and then toggling the button again removes the appended comments and sends it back to the original state.

like image 206
oym Avatar asked Aug 13 '09 00:08

oym


People also ask

How can you remove and HTML element using jQuery?

To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.

Can you delete HTML element in JavaScript?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

What is remove in jQuery?

The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead.


2 Answers

empty() is always an option

jQuery('#main').empty();

like image 117
JLeonard Avatar answered Nov 15 '22 06:11

JLeonard


Give a look at the empty() function.

It might better solve the problem. Here's the link http://api.jquery.com/empty/

like image 45
vidriloco Avatar answered Nov 15 '22 07:11

vidriloco