Home Web Front-end JS Tutorial Detailed explanation of the steps to add, delete and modify JavaScript DOM elements

Detailed explanation of the steps to add, delete and modify JavaScript DOM elements

May 22, 2018 pm 02:32 PM
javascript js Detailed explanation

This time I will bring you JavaScript A detailed explanation of the steps for adding, deleting, and modifying DOM elements. What are the precautions for adding, deleting, and modifying JavaScript DOM elements? The following is a practical case, let’s take a look.

DOM concept

DOM (Document Object Model): Document Object Model.

You can view it through the Elements tab of the developer tool

You can also observe that the entire document has a series of nodes through the Sources tab of the developer tool

The entire document is composed of A tree composed of a series of node objects.

Node (Node) includes element node (1), attribute node (2), text node (3) (1..2..3..represents the node type)_

var th1= document.getElementById("th1");
alert(th1.nodeType);
alert(th1.nodeName);
alert(th1.nodeValue);
Copy after login
th1 represents an element node (nodeType=1), nodeName is the label name (th), and nodeValue=null of the element node.

var attr1=th1.getAttributeNode("name");
alert(attr1.nodeType);
alert(attr1.nodeName);
alert(attr1.nodeValue);
Copy after login
The getAttributeNode method is to get the attribute node of the element. At this time, the output node type is the attribute node (2), the node name is the attribute name (name), and the node value is the attribute value (sex)

var txtl = th1.firstChild;
alert(txtl.nodeType);
alert(txtl.nodeName);
alert(txtl.nodeValue)
Copy after login
txt1 is a text node (3), the node name is fixed to #text, and the node value is the text content.

Get the element

(1)

getElementByid

Get the element based on the id attribute of the element. What you get is a element.

(2)

getElementsByTagName

Get elements based on the tag name, and the result is a collection of elements.

(3)

getElementsByClassName

Get elements based on the class attribute, and the result is a collection of elements.

(4)

getElementsByName

Get elements based on the name attribute, and the result is a collection of elements.

Summary: Obtaining elements can be obtained based on the tag name, or based on the id, name, and class attributes. The result obtained based on the id attribute is an element, while the other results are a collection.

The document object supports the above four types, while the element object only supports

getElementsByTagName and getElementsByClassName.

Modify elements

(1) Modify content

function fun(){
  //获取到指定元素
  var p1 = document.getElementById("p1");
  p1.innerText = "我被单击了!";
}
Copy after login
The content text of the label can be read or set through the .innerText property

function fun(){
  //获取到指定元素
  var p1 = document.getElementById("p1");
  p1.innerHTML = "我被单击了!<br>换行了";
}
Copy after login
You can also get or set the content text through inner

HTML attributes

The difference between the two: innerHTML will parse the text according to HTML rules, while innerText will just treat it as ordinary text content.

(1) Modify style

A. xxx. style.Attribute name="value"

B. xxx. classname="..." (equivalent to modifying the attributes of class)

<style>
    .style1{
      color:red;
      font-size:20px;
      text-decoration:underline;
    }
    .style2{
      color:blue;
      font-size:32px;
      text-decoration:line-through;
    }
  </style>
</head>
<body>
<p id="p1">修改样式测试</p>
<input type="button"value="样式一"onclick="style1()">
<input type="button"value="样式二"onclick="style2()">
</body>
<script>
  var p1 = document.getElementById("p1");
  function style1(){
    p1.className = "style1"
  }
  function style2(){
    p1.className = "style2"
  }
</script>
</html>
Copy after login

Add and delete elements

(1)

CreateElementCreate an element node

CreateElement("p")Create a paragraph

(2)

createTextNodeCreate a text node

createTextNode("Text Content"), create a text node with a value of "Text Content".

(3)

appendChildAdd child node

(4 )

removeChild Delete child node

Dynamic addition

<body>
<p id="p1">
</p>
<input type="button"value="添加段落"onclick="add()">
</body>
<script>
//全局变量
  var index = 1;
  function add(){
    //创建一个段落标签
    var p = document.createElement("p");
    //创建文本节点
    var content= "第"+index+"段落";
    var txt = document.createTextNode(content);
    //创建文本节点添加的段落
    p.appendChild(txt);
    //将段落添加到p中
    var p1 = document.getElementById("p1");
    p1.appendChild(p);
    index++
  }
</script>
Copy after login

Dynamic deletion

<body>
<p id="p1">
  <p id="p1">第1段落 </p>
  <p id="p2">第2段落 </p>
  <p id="p3">第3段落 </p>
  <p id="p4">第4段落 </p>
</p>
<input type="button"value="删除第二段"onclick="del()">
</body>
<script>
  function del(){
    //先找到父节点
    var p1 = document.getElementById("p1");
    //再找到要删除的节点
    var p2 = document.getElementById("p2");
    //将要删除的节点从父节点中移除
    p1.removeChild(p2);
  }
</script>
</html>
Copy after login
This method The method is to find the parent node and the node to be deleted respectively, and then perform the deletion operation. A prerequisite for this method is to know who the parent node is

So if you don’t know who the parent node is, how to delete it

p2.parentNode.removeChild(p2);

This method does not require who the parent node is

Dynamic addition and deletion:

动态添加和动态删除,删除动态添加的奇数段落

思路1:获取p1 下的所以段落,遍历所以的段落,将序号为奇数的段落删除。

function del(){
  var p1 = document.getElementById("p1");
  var paras = p1.getElementsByTagName("p");
  for(var i in paras){
    if((i+1)%2 == 1){
      p1.removeChild(paras[i]);
    }
  }
}
Copy after login

这种在初始时是可以的,但是随着动态添加或删除的进行,后面的结果就不对了。因为动态删除操作就影响了原来的顺序,而程序是按照序号去判断奇偶性,所以出现误判

思路2:添加通过设置class属性,然后通过getElementsByclassName来获取奇数行

(也可以从后往前删)

<body>
<p id="p1">
</p>
<input type="button" value="添加段落" onclick="add()">
<input type="button" value="删除奇数第二段" onclick="de1()">
</body>
<script>
  var index = 1;
  function add(){
    //创建一个段落标签
    var p = document.createElement("p");
    //创建文本节点
    var content = "第" + index + "段落";
    var txt = document.createTextNode(content);
    //将文本节点添加到段落
    p.appendChild(txt);
    if (index % 2 == 1) {
      p.setAttribute("class","odd");
    }
    //将段落添加到p中
    var p1 = document.getElementById("p1");
    p1.appendChild(p);
    index++;
  }
  /*function de1(){
   var p1 = document.getElementById("p1");
   var paras =p1.getElementsByTagName("p");
   for(var i in paras){
   if((i+1)%2 == 1){
   p1.removeChild(paras[i]);
   }
   }
   }*/
  functionde1() {
    var p1 = document.getElementById("p1");
    var paras = p1.getElementsByClassName("odd");
//    varparas = document.getElementsByName("odd");
    for (var i = paras.length - 1; i >= 0; i--) {
      p1.removeChild(paras[i]);
    }
  }
</script>
</html>
Copy after login

导航

Document:是根节点

ParentNode:获取父节点

childNodes:获取所有子节点

firstChild:第一个子节点

lastChlid:获取最后一个子节点

</head>
<body>
<p name="第一章">
   <p id="p1">第一段<span>第一句</span><span>第二句</span></p>
</p>
<input type="button"value="获取父节点的name属性"onclick="fun1()">
<input type="button"value="显示p1子节点的个数"onclick="fun2()">
<input type="button"value="显示p1第一个子节点的类型"onclick="fun3()">
<input type="button"value="显示p1最后一个子节点的类型"onclick="fun4()">
</body>
<script>
var p1 =document.getElementById("p1");
function fun1(){
  var value=p1.parentNode.getAttribute("name");
  alert(value);
}
function fun2(){
  var chlids = p1.childNodes;
  alert(chlids.length)
}
function fun3(){
  alert(p1.firstChild.nodeType);
}
function fun4(){
  alert(p1.lastChild.nodeType);
}
</script>
</html>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

node Async/Await 异步编程实现详解

JS Promise案例代码解析

The above is the detailed content of Detailed explanation of the steps to add, delete and modify JavaScript DOM elements. For more information, please follow other related articles on the PHP Chinese website!

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Detailed analysis of C language learning route Detailed analysis of C language learning route Feb 18, 2024 am 10:38 AM

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles