If you need to delete elements or clear out content dynamically, jQuery makes it painless.
This is highly useful for removing error messages, dismissing pop-ups, or resetting forms.
jQuery contains two primary methods to remove elements and content:
remove() - Removes the selected element entirely (including all its child elements).empty() - Removes the child elements and text from the selected element, but leaves the parent intact.The remove() method deletes the element itself from the DOM.
If you select a <div> and call remove(), the <div> and everything inside it vanishes forever.
$("button").click(function(){
$("#div1").remove();
});
The empty() method only deletes the internal contents of an element.
The parent element stays on the page, ready to be filled with new data later.
$("button").click(function(){
$("#div1").empty();
});
The remove() method also accepts one parameter, which allows you to filter the elements.
The parameter can be any standard jQuery selector syntax.
For instance, you can choose to remove only paragraphs that have a specific class.
// Removes allelements that have class="test" $("p").remove(".test");
This makes precise clean-ups very efficient.
You can even separate multiple filters with a comma: $("p").remove(".test, .demo");
Which method clears out the text and child elements inside a container, but leaves the container itself on the page?