search
HomeWeb Front-endJS TutorialDetailed explanation of jQuery's method of adding and deleting DOM elements_jquery

This article analyzes the jQuery method of adding and removing DOM elements. Share it with everyone for your reference, the details are as follows:

Introduction

DOM is the abbreviation of Document Object Modeule. Generally speaking, DOM operations are divided into three aspects.

1. DOM Core

DOM Core is not exclusive to javascript. Any programming language that supports DOM can use it. Its uses are far beyond just web pages. It can also be used to process any document written using markup language, such as XML.
For example: document,getElementsByTagName("form"); //Use DOM Core to get the form object.

2. HTML-DOM

When using Javascript and DOM to write scripts for HTML files, there are many attributes that belong to HTML-DOM. HTML-DOM appeared even earlier than DOM Core. It provides some more concise notations to describe various HTML The element's properties.
For example:

Copy code The code is as follows:
document.forms //HTML-DOM provides a forms object.

PS: It can be seen that obtaining objects and attributes can be implemented using DOM Core or HTML-DOM.

3. CSS-DOM

CSS-DOM is an operation for CSS. In JavaScript, the main function of CSS-DOM is to obtain and set various attributes of the style object, so that the web page can present various effects.

For example:

Copy code The code is as follows:
element.style.color="red";//Settings Method to set the font color of an element.

Common methods

1. Find element node

Copy code The code is as follows:
var $li = $("ul li:eq(0)");/ /Get the first li under the ul tag, which can also be written as $("#ulID li:eq(0)");

2. Find element attributes

Use jquery's attr() method to obtain the values ​​of various attributes of the element. The parameter of the attr() method can be one or two.

When the parameter is one, it is the name of the attribute to be queried.

When there are two parameters, you can set the value of the attribute.

alert($("#id").attr("title")); //输出元素的title属性.一个参数
$("#id").attr("title","改变title值"); //改变元素的title属性值.二个参数

3. Add element node

$(html) To briefly explain, the $(html) method will create a dom object based on the incoming html tag string, and package the dom object into a jquery object and return it. In short, it will put all the html code of the tag. Just go to the $() factory!

Example:

var $htmlLi = $(" <li title='香蕉'>香蕉</li>"); //创建DOM对象
var $ul = $("ul");  //获取UL对象
$ul.append($htmlLi); //将$htmlLi追加到$ul元素的li列表

Listed below are some methods of inserting nodes

Method

Description

Example

Append()

Append content to each matching element

HTMLCode

    JQueryCode

    $(“ul”).append(“

  • AA
  • ”);

    Results

    • AA
    • appendTo()

      This method is opposite to Append(). a.Append(b) is to replace b is appended to a, and appendTo() is to append b pursues a in

      HTMLCode

        JQueryCode

        $ (“

      • AA
      • ”).appendTo (“ul”).;

        Results

        • AA
        • Prepend()

          Prepend content inside each matched element

          HTMLCode

          Haha

          JQueryCode

          $(“p”).prepend(“ABC”);

          Results

          ABC

          Haha

          prependTo()

          This method is opposite to Prepend(). a. Prepend (b) is to replace b is prepended to a, and prependTo () is to prepend b is prepended to a in

          HTMLCode

          Haha

          JQueryCode

          $(“ABC”).prependTo.(“p”);

          Results

          ABC

          Haha

          After()

          inserts content after each matched element, is after

          HTMLCode

          AAA

          JQueryCode

          $(“p”).After(“cc”);

          Results

          AAA

          cc

          insertAfter()

          is the opposite of After()

          HTMLCode

          AAA

          JQueryCode

          $ (“cc”).After(“p”);

          Results

          AAA

          cc

          Before()

          Insert content before each matching element

          HTMLCode

          AAA

          JQueryCode

          $(“p”). Before (“cc”);

          Results

          cc

          AAA

          insertBefore()

          is the opposite of Before()

          HTMLCode

          AAA

          JQueryCode

          $ (“cc”). insertBefore (“p”);

          Results

          cc

          AAA

          好了,不要斋看,自己动手试试吧:)

          4.删除元素节点

          由于我们需要经常动态去改变DOM元素,因此Jquery提供了两种删除节点的方法,即remove()和empty();

          4.1 remove()方法

          $("p").remove();// 我们可以获取到要删除的元素,然后调用remove()方法
          $("ul li:eq(0)").remove().appendTo("ul");// 删除ul下面的第一个li标记,然后再把删除的li标记重新加到ul里面,remove()方法返回删除元素的引用,这时你可以继续使用
          $("ul li").remove("li[title!=ABC]");//remove可以接受通过参数来选择性的删除符合条件的元素;
          
          

          4.2 empty()方法

          严格来讲,empty()方法并不是删除元素,而是清空

          例:

          HTML代码:

          <ul>
          <li title="AAA">AAA</li>
          </ul>
          
          

          JQuery代码:

          复制代码 代码如下:
          $("ul li:eq(0)").empty();

          结果

          <ul>
          <li title="AAA"></li>
          </ul>
          
          

          记住,只会清空内容,不会请空属性;

          更多关于jQuery操作DOM元素相关内容感兴趣的读者可查看本站专题:《jQuery操作DOM节点方法总结

          希望本文所述对大家jQuery程序设计有所帮助。

          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
          Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

          Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

          Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

          The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

          The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

          JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

          Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

          JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

          The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

          The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

          Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

          Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

          Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

          Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

          JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

          JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

          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

          Video Face Swap

          Video Face Swap

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

          Hot Tools

          Dreamweaver CS6

          Dreamweaver CS6

          Visual web development tools

          EditPlus Chinese cracked version

          EditPlus Chinese cracked version

          Small size, syntax highlighting, does not support code prompt function

          SAP NetWeaver Server Adapter for Eclipse

          SAP NetWeaver Server Adapter for Eclipse

          Integrate Eclipse with SAP NetWeaver application server.

          ZendStudio 13.5.1 Mac

          ZendStudio 13.5.1 Mac

          Powerful PHP integrated development environment

          Zend Studio 13.0.1

          Zend Studio 13.0.1

          Powerful PHP integrated development environment