


Detailed explanation of common addition, deletion, modification and query operations of JS DOM elements
This time I will bring you a detailed explanation of the common addition, deletion, modification and query operations of JS DOM elements. What are the precautions for the common addition, deletion, modification and query operations of JS 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);
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);
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)
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.
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 = "我被单击了!"; }
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>换行了"; }
You can also get or set the content text through innerHTML 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>
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>
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>
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:
Dynamic addition and dynamic deletion, deletion dynamic addition Odd paragraphs
思路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 common addition, deletion, modification and query operations of JS 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

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

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

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

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

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

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

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

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,
