search
HomeWeb Front-endJS TutorialSummary of deletion methods of DOM nodes in jQuery (super comprehensive)

This article mainly introduces the method of deleting DOM nodes in jQuery. I believe the introduction in the article includes the basic usage of empty(), the parameterized and parameterless usage of remove(), the difference between empty and remove, and retention. Friends in need can refer to the data deletion operation detach() and the difference between detach() and remove().

Preface

I believe everyone knows that removing nodes on the page is a common operation for developers. jQuery provides several different methods method is used to deal with this problem. The following article will give a detailed introduction. Friends who are interested can take a look.

1. empty

empty As the name suggests, it is an empty method, but it is a little different from deletion because it only removes All child nodes in the specified element.

This method not only removes child elements (and other descendant elements), but also removes the text within the element. Because, according to the instructions, any text string in the element is regarded as a child node of the element. If we remove all the elements inside p through the empty method, it just clears the inner html code, but the markup still remains in the DOM. Through empty, all p elements under the current p element are removed but the p element itself id=test has not been deleted.

 $("button").on('click', function() {
 //通过empty移除了当前p元素下的所有p元素
 //但是本身id=test的p元素没有被删除
 $("#test").empty()
 })

2. remove

remove is the same method as empty, but remove will Removing the element itself also removes everything inside the element, including bound events and jQuery data related to the element.

For example, a node is bound to a click event. It is actually very simple to delete this node without using the remove method, but at the same time, the event needs to be destroyed. This is to prevent "memory leaks", so front-end developers Be sure to pay attention to how many events are tied up, and remember to destroy them when not in use. Remove p and all elements inside it through the remove method. The event destruction method is automatically operated inside remove, so it is very simple to use.

remove expression parameters:

The advantage of remove over empty is that you can pass a selector expression to filter the set of matching elements to be removed. You can selectively delete specified nodes. We can select a group of the same elements through $(), and then Pass filtering rules through remove(), such as: $("p").filter(":contains('3')").remove().

<body>
 <style>
 .test1 {
 background: #bbffaa;
 }
 
 .test2 {
 background: yellow;
 }
 </style>
 <h2 id="通过jQuery-nbsp-remove方法移除元素">通过jQuery remove方法移除元素</h2>
 <p class="test1">
 <p>p元素1</p>
 <p>p元素2</p>
 </p>
 <p class="test2">
 <p>p元素3</p>
 <p>p元素4</p>
 </p>
 <button>点击通过jQuery的empty移除元素</button>
 <button>点击通过jQuery的empty移除指定元素</button>
 <script type="text/javascript">
 $("button:first").on(&#39;click&#39;, function() {
 //删除整个 class=test1的p节点
 $(".test1").remove()
 })

 $("button:last").on(&#39;click&#39;, function() {
 //找到所有p元素中,包含了3的元素
 //这个也是一个过滤器的处理
 $("p").remove(":contains(&#39;3&#39;)")
 })
 </script>
</body>

The difference between empty and remove

When used to remove specified elements, jQuery provides empty() and remove([expr])Two methods, both delete elements, but there are still differences between the two

empty method

  • Strictly speaking, The empty() method is not to delete the node, but to clear the node. It can clear all descendant nodes in the element

  • empty cannot delete its own node

remove method

  • The node and all descendant nodes contained in the node will be deleted at the same time

  • Provides a filter expression to be passed to specify the elements to be deleted from the selected collection

3. detach

If we want to temporarily delete the node on the page, but do not want the data and events on the node to be lost, and can have the deleted node displayed in the next time period To the page, you can use the detach method to handle detach. It is easy to understand literally. Let a web element be hosted. That is, the element is removed from the current page, but the memory model object of this element is retained.

Official explanation: This method will not delete the matching elements from the jQuery object, so these matching elements can be used again in the future. Unlike remove(), all bound events, attached data, etc. will be retained. $("p").detach()This sentence will remove the object, but the display effect will be gone. But it still exists in memory. When you append, you return to the document flow. It showed up again.

Of course, special attention should be paid here. The detach method is unique to JQuery, so it can only handle events or data bound through JQuery methods

Put all P elements through $("p").detach() After deletion, you can put the deleted p on the page through append and test by clicking on the text. The event is not lost

<body>
 <p>P元素1,默认给绑定一个点击事件</p>
 <p>P元素2,默认给绑定一个点击事件</p>
 <button id="bt1">点击删除 p 元素</button>
 <button id="bt2">点击移动 p 元素</button>
 <script type="text/javascript">
 $(&#39;p&#39;).click(function(e) {
 alert(e.target.innerHTML)
 })
 var p;
 $("#bt1").click(function() {
 if (!$("p").length) return; //去重
 //通过detach方法删除元素
 //只是页面不可见,但是这个节点还是保存在内存中
 //数据与事件都不会丢失
 p = $("p").detach()
 });

 $("#bt2").click(function() {
 //把p元素在添加到页面中
 //事件还是存在
 $("body").append(p);
 });
 </script>
</body>

The difference between detach() and remove()

JQuery is a very powerful tool library. We are developing it at work, but some methods are still ignored by us because they are not commonly used or have not been noticed. remove() and detach() may be one of them. Maybe we use remove() more, while detach() may be used less.

Let’s explain the two methods through a comparison table. The difference between

方法名 参数 事件及数据是否也被移除 元素自身是否被移除
remove 支持选择器表达 是(无参数时),有参数时要根据参数所涉及的范围
detach 参数同remove 情况同remove

remove: Remove node

  • No parameters, remove the entire node itself and all nodes inside the node, including events on the node With parameters

  • , remove the filtered node and all nodes inside the node, including events and data on the node

detach: Remove node

  • The removal process is consistent with remove

  • Different from remove(), all bound events, additional data, etc. will be retained

  • For example: $("p").detach()This sentence will remove the object, just The display effect is gone. But it still exists in memory. When you append, you return to the document flow. It showed up again.

The above is the entire content of this chapter. For more related tutorials, please visit jQuery Video Tutorial!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

jquery中apply()方法怎么用jquery中apply()方法怎么用Apr 24, 2022 pm 05:35 PM

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

jquery on()有几个参数jquery on()有几个参数Apr 21, 2022 am 11:29 AM

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),