jQuery API

.empty()

.empty() Returns: jQuery

Description: Remove all child nodes of the set of matched elements from the DOM.

  • version added: 1.0.empty()

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.

Example:

Removes all child nodes (including text nodes) from all paragraphs

<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>
  Hello, <span>Person</span> <a href="javascript:;">and person</a>
</p>

<button>Call empty() on above paragraph</button>
<script>
  $("button").click(function () {
    $("p").empty();
  });
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .empty() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .empty()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Anonymous

    This is not true about event handlers: “Other jQuery constructs such as data or event handlers are erased as well.”

  • http://www.learningjquery.com/ Karl Swedberg

    Sure it’s true. Admittedly, It’s a little ambiguous about which elements have the data and event handlers removed. The child elements have these constructs removed before the actual elements are removed to prevent memory leaks.

  • Anonymous

    Yes, sorry, my inattention. I mean in case has event handler, $(‘.hello’).empty() won’t remove it.

  • http://tobico.myopenid.com/ Tobias

    empty() removes all data and event handlers from the removed elements. If you want to remove elements without destroying your data or event handlers (so that you can reinsert them later), use detach()

  • Pedro Tiago

    Is this method called before replacing html with .html(html) ?
    I mean… is .html also memory leak safe?

  • Asdf

    LPC

  • lujqke

    is there any way to bring back the content after it has been emptied? Please explain,
    Thank you