The jQuery remove() method removes the selected elements along with the data and events associated with the element. If the selected element has any child node associated with it, remove()
method removes those child nodes as well.
Note: If you only want to remove the selected element and do not want to remove the data and events then use detach() method instead.
If you only want the content of the selected elements removed, then you can use the empty() method.
Syntax of remove() method
$(selector).remove(identifier)
Here identifier is optional, this is to identify the element from the group of the selected elements. For example, to remove all paragraphs, use $("p").remove();
However to remove the paragraph with the class "xyz"
, use $("p").remove(.xyz);
, this will remove the paragraphs with the class "xyz"
.
Example 1: jQuery remove() – remove all p elements
In this example, we are using remove() method to remove all paragraphs.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").remove();
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This example is shared on BeginnersBook.com</p>
<button>Remove all paragraphs</button>
</body>
</html>
Output:
Before “Remove all paragraphs” button click:
After “Remove all paragraphs” button click:
Example 2: jQuery remove() – remove p elements with the specified classes
In this example, we are using remove() method to remove p elements with class “c1” or “c2”.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").remove(".c1, .c2");
});
});
</script>
<style>
.c1 {
color: green;
}
.c2 {
background-color: yellow;
}
</style>
</head>
<body>
<p>This is the first paragraph</p>
<p class="c1">This is the second element with class "c1".</p>
<p class="c2">This is the third paragraph with class "c2".</p>
<p>This is the last paragraph</p>
<button>Remove p elements with class "c1" and "c2"</button>
</body>
</html>
Output:
Before button click:
After button click: You can see that the second and third paragraphs are removed because they had class “c1” or “c2”. More than one p elements can have same class, using remove() with class name will remove all the elements that belong to any of the mentioned classes.