当前位置:网站首页>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
边栏推荐
- Failed to download esp32 program, prompting timeout
- MYCAT configuration
- NPM reports an error: operation not allowed, MKDIR 'C: \ program files \ node JS \ node_ cache _ cacache’
- 653. 两数之和 IV - 输入 BST
- #yyds干货盘点#ubuntu18.0.4安装mysql并解决ERROR 1698: Access denied for user ''root''@''localhost''
- 【SQL server速成之路】数据库的视图和游标
- 《数字电子技术基础》3.1 门电路概述、3.2 半导体二极管门电路
- Unfortunately, I broke the leader's confidential documents and spit blood to share the code skills of backup files
- Cloud computing competition -- basic part of 2020 competition [task 3]
- Kettle experiment conversion case
猜你喜欢

Yyds dry goods inventory ubuntu18 0.4 install MySQL and solve error 1698: access denied for user ''root' '@' 'localhost' '

Kettle experiment conversion case

Mini - exercice MySQL (seulement pour les débutants, pas pour les non - débutants)

Applet error: should have URL attribute when using navigateto, redirectto or switchtab

Detailed explanation of delete, truncate and drop principles in MySQL database

108. 将有序数组转换为二叉搜索树

Machine learning (VI) -- Bayesian classifier

Brush classic topics

Common errors of VMware building es8

MySQL of database -- overview and installation
随机推荐
JS prototype chain
ATSS(CVPR2020)
#yyds干货盘点#ubuntu18.0.4安装mysql并解决ERROR 1698: Access denied for user ''root''@''localhost''
Principle of synchronized implementation
基于ThinkPHP5版本TRC20-资金归集解决方案
《數字電子技術基礎》3.1 門電路概述、3.2 半導體二極管門電路
数据清洗 ETL 工具Kettle的安装
Failed to download esp32 program, prompting timeout
Flink SQL realizes the integration of stream and batch
MySQL - Chapter 1 (data type 2)
高薪程序员&面试题精讲系列91之Limit 20000加载很慢怎么解决?如何定位慢SQL?
Program, process, thread; Memory structure diagram; Thread creation and startup; Common methods of thread
Leetcode0587. 安装栅栏(difficult)
Kettle experiment (III)
ALV树(LL LR RL RR)插入删除
Cloud computing competition -- basic part of 2020 competition [task 3]
Common errors of VMware building es8
Project upload part
Your guide to lowering your cholesterol with TLC (continuously updated)
NPM reports an error: operation not allowed, MKDIR 'C: \ program files \ node JS \ node_ cache _ cacache’