当前位置:网站首页>DOM operation -- operation node
DOM operation -- operation node
2022-07-26 05:26:00 【H5_ ljy】
List of articles
1. Chuangjie dom Elements
Use document.createElement() Method to create an element node
2. Add a node
1.appendChild (); Append the contents of the current element ( Related to the operation process )
2.insertBefore(); Append the element before the old element .
<body>
<div id="div1">
<div id="div2"></div>
</div>
<script>
var div1 = document.getElementById('div1')
var span = document.createElement('span')
var div2 = document.getElementById('div2')
div1.insertBefore(span,div2)
</script>
</body>

Use insertBefore() Method to change the order of nodes
<body>
<ul id="myList"><li>1</li><li>2</li><li>3</li><li>4</li></ul>
<p id="demo"> Click this button to change the order of the list items </p>
<button onclick="fn()"> Am I </button>
<script>
function fn(){
var list=document.getElementById("myList");
var node=list.getElementsByTagName("li");
list.insertBefore(node[3],node[0]);
}
</script>
</body>

3.inserAfter(); Append the element to the old element , The official did not provide this method ;
We encapsulate one by ourselves .
<body>
<div id="div1">
<div id="div2"></div>
</div>
<script>
Object.prototype.insertAfter = function (newnode, existingnode) {
if (this.lastChild == existingnode) {
this.appendChild(newnode);
} else {
this.insertBefore(newnode, existingnode.nextSilbing);
}
}
var span = document.createElement('span')
var div1 = document.getElementById('div1')
var div2 = document.getElementById('div2')
div1.insertAfter(span, div2)

3. Delete node
1. removeChild() Delete child elements
var box=document.querySelector("#box")
box.parentElement.removeChild(box)
2. remove() Delete yourself
var box=document.getElementById("box");
box.remove();
4. Replication node ( Clone node )
The format is as follows :
Nodes to replicate .cloneNode(); // There are no parameters and parameters in brackets false, The effect is the same .
Nodes to replicate .cloneNode(true);
With or without parameters in parentheses , The effect is different . Explain the following :
With no arguments / With parameters false: Just copy the node itself , Do not copy child nodes .
With parameters true: Copy the node itself , Also copy all of its children .
5. Set the properties of a node
1. Get the attribute value of the node
The way 1:
Element nodes . attribute ;
Element nodes [‘ Property name ’];
The way 2:
Element nodes .getAttribute(“ The attribute name ”);
<body>
<img src="../imgs/touxiang.webp.jpg" alt=" Image load failed " title="touxiang" id="img1" class="img_1">
<script>
let img=document.querySelector('.img_1')
console.log(img.src,img['src'])
console.log(img.alt,img['alt'])
console.log(img.title,img['title'])
console.log(img.id,img['id'])
console.log(img.className,img['className'])
console.log(img.getAttribute('src'))
</script>
</body>

2、 Set the attribute value of the node
The way 1:
Element nodes . attribute =‘ Modified value ’;
Element nodes [‘ Property name ’]=‘ Modified value ’;
The way 2:
Element nodes .setAttribute( Property name , New attribute value );
<body>
<img src="../imgs/touxiang.webp.jpg" alt=" Image load failed " title="touxiang" id="img1" class="img_1">
<script>
let img=document.querySelector('.img_1')
img.title='mao'
img.className='img_2' // modify class Name use className
img.setAttribute('id','img2')
console.log(img.title)
console.log(img.className)
console.log(img.id)
</script>
</body>

class Methods of adding and deleting multiple class names :
Mode one :
Element nodes .className=‘ Class name 1 Class name 2’
Element nodes [‘className’]=‘ Class name 1 Class name 2’
Element nodes .className= Element nodes .className+‘ Space class name 2’
Mode two :
Element nodes .classList.add(“ Class name to add ”)
<body>
<img src="../imgs/touxiang.webp.jpg" alt=" Image load failed " title="touxiang" id="img1" class="img_1">
<script>
let img=document.querySelector('.img_1')
img.className='img_1 img_2'
img.className=img.className+' img_3'
img.classList.add("img_4")
img.classList.add("img_4") // Repeat without adding
</script>
</body>

6. Modify the text content of the node
Method 1 :
Element nodes .innerHTML=“<strong> Content <strong>” It will be bold
innerHTML Recognize labels
Method 2 :
Element nodes .innerText=“<strong> Content <strong>” Display the inside quotation marks as a string
innerText You can only parse text and remove spaces and newlines
Summary : Both methods will replace the original content with sub tags , If you don't want to replace the original content, you can :
Element nodes .innerHTML+=“<strong> Content <strong>”
Element nodes .innerText+=“<strong> Content <strong>”
<body>
<div><span>ljy</span></div>
<script>
var div=document.querySelector('div')
div.innerHTML='<strong> Content <strong>'
div.innerText+='<strong> Content <strong>'
</script>
</body>

7. Modify node CSS attribute
Method 1 :
Elements .style. Style name = Style value
Be careful : adopt style Property setting and reading are inline styles , Unable to read styles in style sheet
If CSS The style name of contains -,
This name is used in JS It is illegal in, for example background-color
This style name needs to be changed to hump naming method ,
Get rid of -, And then - The last letter is capitalized
<style>
div{
width: 200px;
height: 200px;
background-color: aqua;
}
</style>
<body>
<div><span>ljy</span></div>
<script>
var div=document.querySelector('div')
console.log(div.style.width,div.style.backgroundColor) // Print empty , Cannot get the style in the style sheet
console.log(div)

Method 2 :
adopt js Read css attribute ( Inline style )
Gets the current display style of the element :
grammar : Elements .currentStyle. Style name
It can be used to read the style that the current element is displaying
If the current element is not set to this style , Then get its default value
currentStyle Only IE Browser support , Other browsers don't support
Available in other browsers
getComputedStyle() This method gets the current style of the element
The method is window Methods , You can use it directly
Two parameters are required
first : The element to get the style
the second : You can pass a pseudo element , It's usually spread null
This method will return an object , Object encapsulates the style corresponding to the current element
Through the object . Style name to read the style
If the obtained style is not set , You will get the real value , Not the default
such as : No settings width, It won't get auto, It's a length
However, this method does not support IE8 And the following browsers
<style>
div{
width: 200px;
height: 200px;
background-color: aqua;
}
</style>
<body>
<div><span>ljy</span></div>
<script>
var div=document.querySelector('div')
let divStyle=getComputedStyle(div)
console.log(divStyle.width,divStyle.height,divStyle.backgroundColor)
</script>
</body>

边栏推荐
猜你喜欢

LNMP架构

Three implementation methods of thread and the usage of handler

C language - Advanced pointer

Chinese character style transfer --- learn the conversion and generation of one to many programmed Chinese characters through generation confrontation network

10. Regular expression matching

Hack the box - Web requests module detailed Chinese tutorial

Recommended reading: how can testers get familiar with new businesses quickly?

OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation

OD-Paper【2】:Fast R-CNN

87. Disturb string
随机推荐
Nacos introduction and deployment
Embedded development notes, practical knowledge sharing
Week 6 Learning Representation: Word Embedding (symbolic →numeric)
Getting started with ALV
Meta analysis [whole process, uncertainty analysis] method based on R language and meta machine learning
Compilation method of flood control evaluation report and flood modeling under the new guidelines
How to understand "array name is essentially an address" from the perspective of memory parsing?
FPGA刷题——序列检测
Computable general equilibrium (CGE) model practice technology in resource environment under the goal of "double carbon"
Hack The Box -SQL Injection Fundamentals Module详细讲解中文教程
MongoDB 常用命令
SQL injection
Princeton calculus reader 02 Chapter 1 -- composition of functions, odd and even functions, function images
Hack The Box - Web Requests Module详细讲解中文教程
Webassembly 01 basic information
开发转测试:从零开始的6年自动化之路
Practical technology of SWAT Model in simulation of hydrology, water resources and non-point source pollution
C语言实现发牌功能基本方法
攻防世界--easy_web
no networks found in /etc/cni/net.d