


Detailed explanation of the steps to add, delete and modify JavaScript DOM elements
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 toolYou can also observe that the entire document has a series of nodes through the Sources tab of the developer toolThe 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);
var attr1=th1.getAttributeNode("name"); alert(attr1.nodeType); alert(attr1.nodeName); alert(attr1.nodeValue);
var txtl = th1.firstChild; alert(txtl.nodeType); alert(txtl.nodeName); alert(txtl.nodeValue)
Get the element
(1)getElementByid
Get the element based on the id attribute of the element. What you get is a element. (2)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 supportsgetElementsByTagName and
getElementsByClassName.
Modify elements
(1) Modify contentfunction fun(){ //获取到指定元素 var p1 = document.getElementById("p1"); p1.innerText = "我被单击了!"; }
function fun(){ //获取到指定元素 var p1 = document.getElementById("p1"); p1.innerHTML = "我被单击了!<br>换行了"; }
<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>
Add and delete elements
(1)CreateElementCreate an element node
CreateElement("p")Create a paragraph
createTextNodeCreate a text node
createTextNode("Text Content"), create a text node with a value of "Text Content".
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>
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>
p2.parentNode.removeChild(p2);
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]); } } }
这种在初始时是可以的,但是随着动态添加或删除的进行,后面的结果就不对了。因为动态删除操作就影响了原来的顺序,而程序是按照序号去判断奇偶性,所以出现误判
思路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>
导航
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>
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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 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'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

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: 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.
