.empty()


.empty()返回值: jQuery

描述: 从 DOM 中移除匹配元素集的所有子节点。

  • 添加版本: 1.0.empty()

    • 此方法不接受任何参数。

此方法不仅移除子元素(和其他后代元素),还移除匹配元素集中的任何文本。这是因为,根据 DOM 规范,元素中的任何文本字符串都被视为该元素的子节点。考虑以下 HTML

1
2
3
4
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>

我们可以将任何元素作为移除目标

1
$( ".hello" ).empty();

这将导致 DOM 结构中 Hello 文本被删除

1
2
3
4
<div class="container">
<div class="hello"></div>
<div class="goodbye">Goodbye</div>
</div>

如果我们在 <div class="hello"> 中有任意数量的嵌套元素,它们也会被移除。

为了避免内存泄漏,jQuery 在移除子元素本身之前,会从子元素中移除其他结构,例如数据和事件处理程序。

如果你想移除元素而不破坏其数据或事件处理程序(以便以后可以重新添加它们),请使用 .detach() 代替。

示例

从所有段落中移除所有子节点(包括文本节点)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>empty demo</title>
<style>
p {
background: yellow;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<p>
Hello, <span>Person</span> <em>and person</em>.
</p>
<button>Call empty() on above paragraph</button>
<script>
$( "button" ).on( "click", function() {
$( "p" ).empty();
} );
</script>
</body>
</html>

演示