jQuery Remove

In jQuery, you can easily remove elements from the DOM using several methods.


Remove Elements/Content


Method

Description

.remove()

Removes the selected element(s) from the DOM completely.

.empty()

Removes all child elements from the selected element(s) but keeps the element itself.

jQuery remove() Method


The .remove() method completely removes the selected element(s) and their associated data, events, and content from the DOM.

Example
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").remove(); // Removes the <p> element completely from #myDiv
});
});
</script>

Try it yourself

jQuery empty() Method


The .empty() method removes all child elements inside the selected element but keeps the selected element itself.

Example
<script>
$(document).ready(function(){
$("button").click(function(){
$("#myDiv").empty(); // Removes all <p> elements inside #myDiv but keeps #myDiv itself
});
});
</script>

Try it yourself

Filter the Elements to be Removed


In jQuery, you can filter elements before removing them using selectors or functions inside the .remove() method. This allows you to remove only specific elements from a group.


The following example removes all <p> elements with class="remove":  

Example
<script>
$(document).ready(function(){
$("#removeBtn").click(function(){
$("p").remove(".removeMe"); // Only removes paragraphs with class="removeMe"
});
});
</script>

Try it yourself

This example removes all <p> elements with class="removeMe" and class="removeMeAlso":  

Example
<script>
$(document).ready(function(){
$("#removeBtn").click(function(){
$("p").remove(".removeMe, .removeMeAlso"); // Only removes paragraphs with class="removeMe"
});
});
</script>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.