We can use the jQuery empty method to clear all of the child elements of an HTML div/element.
$("#div1").empty();
Let’s say I have the following HTML:
<div id="div1">
<p>This is a paragraph with some text.</p>
<p>This is a paragraph with some text.</p>
<p>This is a paragraph with some text.</p>
<p>This is a paragraph with some text.</p>
</div>
If we want to remove all of the paragraphs from the div, #div1, we can use the jQuery empty() method to do this with the following jQuery code.
$("#div1").empty();
The resulting HTML would be as follows:
<div id="div1"></div>
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").empty();
Using the jQuery empty() method to remove all elements from a Div with a click
We can remove all elements from a specific HTML element using jQuery very easily by combining the empty() method with a click event.
Let’s say we have the following HTML code and we want to give the user the ability to remove all paragraphs and divs from the main div.
<style>#div1 { border: 1px solid #000; padding: 10px; } .boxes { width: 200px; height: 200px; margin-bottom: 10px; background: #82b5be; }</style>
<div id="div1">
<p>This is the paragraph we will remove.</p>
<p>This is the paragraph we will remove.</p>
<div class="boxes">This box will be removed.</div>
<p>This is the paragraph we will remove.</p>
<p>This is the paragraph we will remove.</p>
</div>
<div id="click-me">Empty div above</div>
Below is the JavaScript code which will allow the user to be able div, #div1:
$("#click-me").click(function(){
$("#div1").empty();
});
The final code and output for this example of how to empty a specific div using jQuery and JavaScript is below:
Code Output:
This is the paragraph we will remove.
This is the paragraph we will remove.
This is the paragraph we will remove.
This is the paragraph we will remove.
Full Code:
<style>#div1 { border: 1px solid #000; padding: 10px; } .boxes { width: 200px; height: 200px; margin-bottom: 10px; background: #82b5be; }</style>
<div id="div1">
<p>This is the paragraph we will remove.</p>
<p>This is the paragraph we will remove.</p>
<div class="boxes">This box will be removed.</div>
<p>This is the paragraph we will remove.</p>
<p>This is the paragraph we will remove.</p>
</div>
<div id="click-me">Empty div above</div>
<script>
$("#click-me").click(function(){
$("#div1").empty();
});
</script>
Hopefully this article has been useful for you to understand how to use jQuery to remove an element.
Leave a Reply