


Summary 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('click', function() { //删除整个 class=test1的p节点 $(".test1").remove() }) $("button:last").on('click', function() { //找到所有p元素中,包含了3的元素 //这个也是一个过滤器的处理 $("p").remove(":contains('3')") }) </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 elementempty 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"> $('p').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 retainedFor 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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!