search
HomeWeb Front-endJS TutorialDetailed example of the difference between empty and remove based on DOM

This article mainly brings you an article on the difference between empty and remove based on DOM node deletion (detailed explanation). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Removing nodes on the page is a common operation for developers. jQuery provides several different methods to deal with this problem. Here we take a closer look at the empty and remove methods

empty As the name suggests, the clear method 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 description, any text string in an element is regarded as a child node of the element. Please look at the following HTML:

<p></p><p>这是p标签</p>

If we remove all elements inside p via empty method, it just clears the inner html code, but the markup still remains in the DOM

//通过empty处理
$('.hello').empty()

//结果:<p>这是p标签</p>被移除
<p></p>

via empty All p elements under the current p element have been removed, but the p element with id=test has not been deleted.

nbsp;html>



  <meta>
  <title></title>
  <script></script>
  <style>
  p {
    background: #bbffaa;
    width: 300px;
  }
  </style>



  <h2 id="通过empty移除元素">通过empty移除元素</h2>
  <p>
    </p><p>p元素1</p>
    <p>p元素2</p>
  
  <button>点击通过jQuery的empty移除元素</button>
  <script>
  $("button").on(&#39;click&#39;, function() {
    //通过empty移除了当前p元素下的所有p元素
    //但是本身id=test的p元素没有被删除
    $("#test").empty()
  })
  </script>


remove is the same as empty. It is a method of removing elements, but remove will move the element itself. Removes everything inside the element, including bound events and jQuery data associated with the element.

For example, for a node, bind a click event

<p></p><p>这是P段落</p>
$('.hello').on("click",fn)

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 must pay attention to how many events are tied and remember to destroy them when not in use

Remove p and all its internal elements through the remove method. The event destruction method will be automatically operated inside remove, so It is very simple to use

//通过remove处理
$('.hello').remove()
//结果:<p></p><p>这是P段落</p> 全部被移除 //节点不存在了,同事事件也会被销毁

remove expression parameters:

The advantage of remove than empty is that you can pass a selector expression to filter the set of matching elements that will be removed. You can selectively delete specified nodes

We can select a group of the same elements through $(), and then pass the filtering rules through remove(), so as to handle this

nbsp;html>



  <meta>
  <title></title>
  <script></script>
  <style>
  .test1 {
    background: #bbffaa;
  }
  
  .test2 {
    background: yellow;
  }
  </style>



  <h2 id="通过jQuery-remove方法移除元素">通过jQuery remove方法移除元素</h2>
  <p>
    </p><p>p元素1</p>
    <p>p元素2</p>
  
  <p>
    </p><p>p元素3</p>
    <p>p元素4</p>
  
  <button>通过点击jQuery的empty移除元素</button>
  <button>通过点击jQuery的empty移除指定元素</button>
  <script>
  $("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>


To be used When removing specified elements, jQuery provides two methods, empty() and remove([expr]). Both of them delete elements, but there are still differences between them:

To use remove specification When it comes to elements, jQuery provides two methods: empty() and remove([expr]). Both of them delete elements, but there are still differences between them.

empty method

Strictly In other words, the empty() method does not delete the node, but clears the node. It can clear all descendant nodes in the element.

empty cannot delete its own node

remove method

This node and all descendant nodes contained in this node will be deleted at the same time

Provides a filtering expression to be passed to delete elements in the specified collection

The above is the difference between the two. We will deepen our understanding through the code part below

nbsp;html>



  <meta>
  <title></title>
    <script></script>
  <style>
  .left,
  .right {
    width: 300px;
  }
  
  .left p,
  .right p {
    width: 100px;
    height: 90px;
    padding: 5px;
    margin: 5px;
    float: left;
    border: 1px solid #ccc;
  }
  
  .left p {
    background: #bbffaa;
  }
  
  .right p {
    background: yellow;
  }
  </style>



  <h2 id="通过empty与remove移除元素">通过empty与remove移除元素</h2>
  <p>
    <button>点击通过jQuery的empty移除内部P元素</button>
    <button>点击通过jQuery的remove移除整个节点</button>
  </p>
  <p>
    </p><p>
      </p><p>p元素1</p>
      <p>p元素2</p>
    
    <p>
      </p><p>p元素3</p>
      <p>p元素4</p>
    
  
  <script>
  $("#bt1").on(&#39;click&#39;, function() {
    //删除了2个p元素,但是本着没有删除 
    $("#test1").empty()
  })

  $("#bt2").on(&#39;click&#39;, function() {
    //删除整个节点
    $("#test2").remove()
  })
  </script>


Related recommendations:

Introduction to the functions is_null, isset, and empty in php

Questions about empty-cells in css

Detailed analysis of the empty-cells attribute in css table

The above is the detailed content of Detailed example of the difference between empty and remove based on DOM. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

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

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),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.