当前位置:网站首页>JS node operation, why learn node operation
JS node operation, why learn node operation
2022-04-23 09:27:00 【Small white egg tart】
How to get elements
1.DOM The way
The logic is not strong , tedious
<div>woshi1</div>
<span>woshispan</span>
<ul>
<li> I am a Li</li>
<li> I am a Li</li>
<li> I am a Li</li>
<li> I am a Li</li>
</ul>
<div class="box">
<span class="er"></span>
</div>
We need to get... One by one Like getting var ul = document.querarySelector('div'), And get ul Inside li, We have to write var lis = ul.querySelectorAll('li'), More complicated
2. Use the hierarchical relationship of nodes , Father, son and brother
Strong logic , But compatibility is poor
node
Everything in the page is a node
Node has at least nodeType( Node type )、nodeName( The name of the node )、nodeValue( Node values )
Element nodes nodeType by 1, Attribute node 2, Content node 3, We mainly operate on element nodes .
Node operation - Parent node parentNode
Returns the nearest parent node , No return found null
<div class="box">
<span class="er"></span>
</div>
<script>
// Parent node parentNode
var er = document.querySelector('.er');
// var box = document.querySelector('.box'); Before
// Get the parent node The parent node closest to the element No return found null
console.log(er.parentNode);
</script>

Node operation - Child node
childNodes Get everything ( Pro - ) Child node , Including element nodes, text nodes, attribute nodes, etc
<ul>
<li class="lii">woshi1i</li>
<li>woshi1i</li>
<li>woshi1i</li>
<li>woshi1i<span>123</span></li>
</ul>
// Dom
var ul = document.querySelector('ul');
// var lis = document.querySelectorAll('li');// Before
// Child node childNodes Get all the child nodes , Including element nodes, text nodes and so on
console.log(ul.childNodes);


If you just want to get the element node , Special treatment required ( By judgment nodeType Is it equal to 1), Therefore, the use of childNodes.
Just want to get the element node , use children( Nonstandard ), frequently-used
ul.children

Node operation - The first and last child elements
firstChild The first child node, whatever it is ,firstElementChild and lastElementChild You can get the first child element node and the last child element node , But they are compatible .
In development , We often use ul.children[0] To return the first child element node ,ul.children[ul.children.length-1] The last child element node , There is no compatibility .
Node operation - Brother node
nextSibling Next sibling node ( All include )
previousSibling,nextElementSibling,previousSibling All have compatibility issues
Node operation - Create and add nodes
1.document.createElement('tagName')
2. Add to where ?
node.appendChild(child),node Append element after .node.insertBefore(child, Specify elements )
node It's a parent ,child It's a child
<body>
<ul>
<li>123</li>
</ul>
<script>
// document.createElement('tagName')
// Create nodes
var li = document.createElement('li');
// Add a node node.appendChild(child) node Parent child Sub level
var ul = document.querySelector('ul');
ul.appendChild(li); // Append element after
// Want to be in li123 Add node.insertBefore(child, Specify elements )
var lii = document.createElement('li');
ul.insertBefore(lii, ul.children[0]);
</script>
</body>
Node operation - Delete node
node.removeChild(child)
prevent a Link jump ,href="javascript:;" perhaps javascript:void(0)
Case study : Simple message board
<body>
<textarea name="" id="" cols="30" rows="10"></textarea>
<button> Release </button>
<ul>
<!-- <li></li> -->
</ul>
<script>
// Get elements
var btn = document.querySelector('button');
var text = document.querySelector('textarea');
var ul = document.querySelector('ul');
// Registration events
btn.onclick = function() {
if (text.value == '') {
alert(' You have not entered ');
return false;
} else {
// console.log(text.value);
// Create elements
var li = document.createElement('li');
li.innerHTML = text.value + "<a href='javascript:;'> Delete </a>"; //Z To prevent link jump, you need to add javascript:; perhaps javascript:void(0);
// // Additive elements
// ul.appendChild(li);
ul.insertBefore(li, ul.children[0]);
// Remove elements Currently linked li
var as = document.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
// Delete a Where li
ul.removeChild(this.parentNode);
}
}
}
}
</script>
</body>

Case study : Dynamically generate tables
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
width: 500px;
margin: 100px auto;
/* border-collapse: collapse; */
text-align: center;
}
td,
th {
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: #ccc;
}
</style>
</head>
<body>
<table cellspacing="0">
<thead>
<tr>
<th> full name </th>
<th> subject </th>
<th> achievement </th>
<th> operation </th>
</tr>
</thead>
<tbody>
Dynamically generated There is no need for
<!-- <tr>
<td> Wei Yingluo </td>
<td>JS</td>
<td>100</td>
<td><a href="#"> Delete </a></td>
</tr>
<tr>
<td> Xiaolan </td>
<td>JS</td>
<td>70</td>
<td><a href="#"> Delete </a></td>
</tr>
<tr>
<td> Xiaohong </td>
<td>JS</td>
<td>30</td>
<td><a href="#"> Delete </a></td>
</tr>
<tr>
<td> Xiao Ming </td>
<td>JS</td>
<td>10</td>
<td><a href="#"> Delete </a></td>
</tr> -->
</tbody>
</table>
<script>
//1. Prepare student data
var datas = [{
name: ' Xiao Ming ',
subject: 'JS',
score: 100
}, {
name: ' Small column ',
subject: 'JS',
score: 30
}, {
name: ' cockroach ',
subject: 'JS',
score: 90
}, {
name: ' Less than ',
subject: 'JS',
score: 45
}]
// Put all the data into tbody The line inside First row, then cell
// 2、 establish tr That's ok
var tb = document.querySelector('tbody');
for (var i = 0; i < datas.length; i++) {
var tr = document.createElement('tr');
// Generated 4 Row
tb.appendChild(tr);
// Create cells Data related td The number depends on the number of attributes
for (var k in datas[i]) { // External circulation and internal circulation
var td = document.createElement('td');
// When creating a cell, give the attribute value in the object to td
tr.appendChild(td);
td.innerHTML = datas[i][k];
}
// Create cells with deletions
var td = document.createElement('td');
td.innerHTML = '<a href="javascript:;"> Delete </a>';
tr.appendChild(td);
var as = document.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
tb.removeChild(this.parentNode.parentNode);
}
}
}
</script>
</body>


版权声明
本文为[Small white egg tart]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230624113928.html
边栏推荐
- Rembg split mask
- 机器学习(六)——贝叶斯分类器
- Yyds dry goods inventory ubuntu18 0.4 install MySQL and solve error 1698: access denied for user ''root' '@' 'localhost' '
- NLLLoss+log_ SoftMax=CE_ Loss
- 亚马逊云科技入门资源中心,从0到1轻松上云
- Summary of common concepts and problems of linear algebra in postgraduate entrance examination
- 653. Sum of two IV - input BST
- [SQL Server fast track] view and cursor of database
- Secrets in buffctf file 1
- [boutique] using dynamic agent to realize unified transaction management II
猜你喜欢

《信息系统项目管理师总结》第八章 项目干系人管理

Go language learning notes - exception handling | go language from scratch
![[in-depth good article] detailed explanation of Flink SQL streaming batch integration technology (I)](/img/c9/43a63f526068ef6a3e4964a22c5a1f.png)
[in-depth good article] detailed explanation of Flink SQL streaming batch integration technology (I)

如何实现根据照片获取地理位置及如何防御照片泄漏地理位置

Secrets in buffctf file 1

Leetcode0587. 安装栅栏(difficult)

How to protect open source projects from supply chain attacks - Security Design (1)

SAP 101K 411k inventory change

Summary of wrong questions 1

Production practice elk
随机推荐
[reading notes] Chapter 5 conditional statements, circular statements and block statements of Verilog digital system design tutorial (with answers to thinking questions)
Set the maximum width of the body, but why does the background color of the body cover the whole page?
Applet error: should have URL attribute when using navigateto, redirectto or switchtab
108. 将有序数组转换为二叉搜索树
Number theory to find the sum of factors of a ^ B (A and B are 1e12 levels)
Principle of synchronized implementation
Go language learning notes - exception handling | go language from scratch
#yyds干货盘点#ubuntu18.0.4安装mysql并解决ERROR 1698: Access denied for user ''root''@''localhost''
The most concerned occupations after 00: civil servants ranked second. What was the first?
kettle实验
LeetCode396. Rotate array
Production practice elk
Go language learning notes - array | go language from scratch
Cloud computing competition -- basic part of 2020 competition [task 3]
Your guide to lowering your cholesterol with TLC (continuously updated)
Group Backpack
DMP engine work summary (2021, lightsaber)
Number of islands
JSON input of Chapter 14 of kettle paoding jieniu
如何实现根据照片获取地理位置及如何防御照片泄漏地理位置