Main Tutorials

jQuery empty() and remove() example

Both jQuery empty() and remove() are used to remove the matched elements, just the former is used to remove the child of the matched elements; while the latter is used to remove all the matched elements totally.

Example

2 div tags – “BBox” is a child element to “ABox”.


<div class="ABox">
	I'm a A box
	<div class="BBox">I'm a B box</div>
</div>

1. empty()

The empty() will remove “ABox” contents and the “BBox” child elements only.


$('.ABox').empty();

The new result will be :


<div class="ABox">
</div>

2. remove()

The remove() will remove all the “ABox” and “BBox” elements totally.


$('.ABox').remove();

The new result will be :


//nothing left

Try it yourself


<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	.ABox{
		padding:8px;
		border:1px solid blue;
	}
	.BBox{
		padding:8px;
		border:1px solid red;
	}
</style>

</head>
<body>
  <h1>jQuery empty() and remove() example</h1>

  <div class="ABox">
	I'm a A box
	<div class="BBox">I'm a B box</div>
   </div>
  
  <p>
  <button id="empty">empty()</button>
  <button id="remove">remove()</button>
  <button id="reset">reset</button>
  </p>
  
<script type="text/javascript">
	
    $("#reset").click(function () {
	  location.reload();
    });
	
    $("#empty").click(function () {
		
	  $('.ABox').empty();
	  
    });
	
    $("#remove").click(function () {
		
	  $('.ABox').remove();
	  
    });
	
	
</script>
</body>
</html>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Ken Schumack
10 years ago

Excellent tutorial. Thank you!