jQuery - 删除元素


jQuery 提供了remove()empty()方法来从HTML 文档中删除现有的HTML 元素。

jQuery的remove()方法

jQuery的remove()方法从文档中删除选定的元素及其子元素。

以下是remove()方法的语法:

$(selector).remove();

当您想要删除元素本身及其内部的所有内容时,应该使用remove()方法。

概要

考虑以下 HTML 内容:

<div class="container"> <h2>jQuery remove() Method</h2> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div>

现在,如果我们按如下方式应用remove()方法:

$( ".hello" ).remove();

它将产生以下结果:

<div class="container"> <h2>jQuery remove() Method</h2> <div class="goodbye">Goodbye</div> </div>

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

例子

让我们尝试以下示例并验证结果:

<!doctype html> <html> <head> <title>The jQuery Example</title> <script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script> <script> $(document).ready(function() { $("button").click(function(){ $( ".hello" ).remove(); }); }); </script> </head> <body> <div class="container"> <h2>jQuery remove() Method</h2> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div> <br> <button>Remove Text</button> </body> </html>

用过滤器去除

我们还可以包含一个选择器作为remove()方法的可选参数。例如,我们可以将之前的 DOM 删除代码重写如下:

让我们尝试以下示例并验证结果:

<!doctype html> <html> <head> <title>The jQuery Example</title> <script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script> <script> $(document).ready(function() { $("button").click(function(){ $("div").remove(".hello"); }); }); </script> </head> <body> <div class="container"> <h2>jQuery remove(selector) Method</h2> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div> <br> <button>Remove Text</button> </body> </html>

jQueryempty() 方法

jQuery的empty()方法与remove()非常相似,它从文档中删除选定的元素及其子元素。此方法不接受任何参数。

以下是empty()方法的语法:

$(selector).empty();

当您想要删除元素本身及其内部的所有内容时,应该使用empty()方法。

概要

考虑以下 HTML 内容:

<div class="container"> <h2>jQuery empty() Method</h2> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div>

现在,如果我们应用empty()方法,如下所示:

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

它将产生以下结果:

<div class="container"> <h2>jQuery empty() Method</h2> <div class="goodbye">Goodbye</div> </div>

例子

让我们尝试以下示例并验证结果:

<!doctype html> <html> <head> <title>The jQuery Example</title> <script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script> <script> $(document).ready(function() { $("button").click(function(){ $( ".hello" ).empty(); }); }); </script> </head> <body> <div class="container"> <h2>jQuery empty() Method</h2> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div> <br> <button>Remove Text</button> </body> </html>

jQuery HTML/CSS 参考

您可以在以下页面获取操作 CSS 和 HTML 内容的所有 jQuery 方法的完整参考:jQuery HTML/CSS 参考