Description:
Remove all child nodes from the set of matched elements.
Note that this function starting with 1.2.2 will also remove all event handlers and internally cached data.
.empty()
version added: 1.0
This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element. Consider the following HTML:
<div class="container"> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div>
We can target any element for removal:
$('.hello').empty();
This will result in a DOM structure with the Hello text deleted:
<div class="container"> <div class="hello"></div> <div class="goodbye">Goodbye</div> </div>
If we had any number of nested elements inside <div class="hello">, they would be removed, too.
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
Examples
Removes all child nodes (including text nodes) from all paragraphsFull source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("button").click(function () {
$("p").empty();
});
});
</script>
<style>
p { background:yellow; }
</style>
</head>
<body>
<p>
Hello, <span>Person</span> <a href="javascript:;">and person</a>
</p>
<button>Call empty() on above paragraph</button>
</body>
</html>
Was this information helpful?

