jQuery Methods for Removing Elements
jQuery detach() Method
The detach()
method removes all text and child nodes from the selected elements. It does, however, save data and events.
This method also saves a copy of the elements that have been removed, allowing them to be reinserted later.
Syntax of detach method in jQuery
$(selector).detach()
Example of jQuery detach method
Remove all
elements from the code:
$("button").click(function(){
$("p").detach();
});
Tip 1: Use the remove()
method instead to remove the elements, their data, and events.
Tip 1: Use the empty()
method to remove only the content from the selected elements.
jQuery empty() Method
The empty()
method clears the selected elements of all child nodes and content. However, the piece itself, as well as its attributes, are not removed by this method.
Syntax of empty method in jQuery
$(selector).empty()
Example of jQuery empty method
Remove all of the
$("button").click(function(){
$("div").empty();
});
Tip: Use the detach()
method to remove elements without removing data or events.
Tip: Use the remove()
method to remove the elements and their data and events.
jQuery remove() Method
The remove()
method removes all text and child nodes from the selected elements.
This method also removes the selected elements' data and events.
Syntax of remove method in jQuery
$(selector).remove(selector)
Example of jQuery remove method
Remove all
elements:
$("button").click(function(){
$("p").remove();
});
Tip: Instead, use the detach()
method to remove elements without removing data and events.
Tip: Use the empty()
method to remove only the content from the selected elements.