.empty()

.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 does not accept any arguments.

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.

If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach() instead.

Example:

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

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>empty demo</title>
  <style>
  p {
    background: yellow;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js" rel="external nofollow" ></script>
</head>
<body>
 
<p>
  Hello, <span>Person</span> <em>and person</em>.
</p>
 
<button>Call empty() on above paragraph</button>
 
<script>
$( "button" ).click(function() {
  $( "p" ).empty();
});
</script>
 
</body>
</html>

Demo:

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquery.com/empty

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部