The jQuery empty() method removes the content of the selected elements. If the selected elements have any child nodes, empty()
method removes those child nodes as well. This method doesn’t remove the element itself, it just removes the content of the element.
Note: If you want to remove the elements along with the data and events, use remove() method instead.
If you only want to remove the selected element and do not want to remove the data and events then use detach() method instead.
Syntax of empty() method
$(selector).empty()
$(selector), selected the elements that require the content to be removed. Read more about jQuery selectors here.
Example 1: jQuery empty() method
In the following example, we have a div element and there are some elements on the page that are inside this ‘div’ such as a p element and a list. We are using the empty() method to clear the content of div element.
<!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(){
$("div").empty();
});
});
</script>
</head>
<body>
<div style="height:150px;">
<p>Paragraph inside div element.</p>
List inside div element:
<ul>
<li>ListItem1</li>
<li>ListItem2</li>
<li>ListItem3</li>
<li>ListItem4</li>
</ul>
</div>
<p>Paragraph outside the div element.</p>
<button>Remove the content inside div element</button>
</body>
</html>
Output:
Before button click:
After button click: As you can see the paragraph and list inside ‘div’ element are removed from the page and the elements outside ‘div’ are still on the page.
Example 2: jQuery empty() method – Remove content of ‘this’ element
In the following example, we are removing the content of ‘this’ element. Here keyword ‘this’ represents the current element. In the above example, we specifically mentioned ‘div’ element while using empty(). Here we are using ‘this’ to apply empty() on any element that is being interacted by the user.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).empty();
});
});
</script>
</head>
<body>
<p><b><i>Paragraph 1: click here to remove it</b></i></p>
<p><b><i>Paragraph 2: click here to remove it</b></i></p>
<p><b><i>Paragraph 3: click here to remove it</b></i></p>
</body>
</html>
Output:
Before any click:
After the user clicks on ‘Paragraph 2’: When the user clicked on the second paragraph, it got removed from the page.