jQuery Remove Elements & Attribute

jQuery Remove Elements or Contents

jQuery offers several methods like empty(), remove(), unwrap(), and more to delete existing HTML elements or content from the document.

jQuery empty() Method

The 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.


jQuery remove() Method

The 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.


jQuery unwrap() Method

The 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>

jQuery removeAttr() Method

The 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>