jQuery offers several methods like empty()
, remove()
, unwrap()
, and more to delete existing HTML elements or content from the document.
empty()
MethodThe jQuery empty()
method gets rid of all child elements, descendant elements, and text content within the selected elements from the DOM.
In the example below, clicking the button will clear all content inside elements with the class .container
.
<script>
$(document).ready(function(){
// Empty container element
$("button").click(function(){
$(".container").empty();
});
});
</script>
Note: As per the W3C (World Wide Web Consortium) DOM specification, any text string within an element is regarded as a child node of that element.
remove()
MethodThe jQuery remove()
method deletes the selected elements from the DOM, including everything inside them. Along with the elements, all associated events and jQuery data are also removed.
In the example below, clicking the button will remove all <p>
elements with the class .hint
from the DOM. Any nested elements within these paragraphs will also be removed.
<script>
$(document).ready(function(){
// Removes paragraphs with class "hint" from DOM
$("button").click(function(){
$("p.hint").remove();
});
});
</script>
The jQuery remove()
method can also take a selector as an optional parameter, which lets you filter the elements to be removed. For example, the previous jQuery DOM removal code could be rewritten like this:
<script>
$(document).ready(function(){
// Removes paragraphs with class "hint" from DOM
$("button").click(function(){
$("p").remove(".hint");
});
});
</script>
Note: You can also use a selector expression as a parameter within the jQuery remove()
method, such as remove(".hint, .demo")
, to filter multiple elements.
unwrap()
MethodThe jQuery unwrap()
method removes the parent elements of the selected elements from the DOM. This usually works as the opposite of the wrap()
method.
In the example below, clicking the button will remove the parent element of <p>
elements.
<script>
$(document).ready(function(){
// Removes the paragraph's parent element
$("button").click(function(){
$("p").unwrap();
});
});
</script>
removeAttr()
MethodThe jQuery removeAttr()
method deletes an attribute from the selected elements.
The example below will remove the href
attribute from the <a>
elements when the button is clicked.
<script>
$(document).ready(function(){
// Removes the hyperlink's href attribute
$("button").click(function(){
$("a").removeAttr("href");
});
});
</script>