Home Web Front-end JS Tutorial Summary of deletion methods of DOM nodes in jQuery (super comprehensive)

Summary of deletion methods of DOM nodes in jQuery (super comprehensive)

May 16, 2016 pm 05:04 PM
jquery

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()
 })
Copy after login

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>通过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>
Copy after login

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>
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles