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:
This is a paragraph with some text.
This is a paragraph with some text.
This is a paragraph with some text.
This is a paragraph with some text.
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:
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.
This is the paragraph we will remove.
This is the paragraph we will remove.
This box will be removed.
This is the paragraph we will remove.
This is the paragraph we will remove.
Empty div above
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:
This is the paragraph we will remove.
This is the paragraph we will remove.
This box will be removed.
This is the paragraph we will remove.
This is the paragraph we will remove.
Empty div above
Hopefully this article has been useful for you to understand how to use jQuery to remove an element.