dom的遍历
由于dom是多叉树,所以不适合前序、中序、后序遍历,我们一般采用 深度、广度优先遍历,其中这两种遍历的实现都有递归与非递归两种方法
<div class="wrapper"><section class="header"><div class="logo"></div></section><section class="main"><div class="sidebar"><ul class="menu"><li class='li'><!-- 目标节点 --><a href="" id='demo'>li1-a</a></li><li class='li'><a href="">li2</a></li></ul></div></section><section class="footer"><div class="copyright"></div></section></div>
深度优先
从根节点出发,选择一条路走到底,然后往上逐个回溯,看有没有第二条路径
递归
必备api:node.children => []
每层的node,循环解决,当循环到当前节点时,递归深入
结束: node.children 无子节点
const root = document.querySelector('.wrapper');
DFS(root);
function DFS(node){
let visited = new Map();
DFSCall(node);
console.log(visited);
function DFSCall(node){
visited.set(node,1); // set 自带去重功能
for(let next_nodes of node.children) {
DFSCall(next_nodes);
}
}
}

非递归
使用stack充当递归栈的作用
把每层node.children读取出来的要遍历的节点 放入待遍历栈
稍微有点不一样的深度优先遍历,从右边开始的
const root = document.querySelector('.wrapper');
console.log(root);
DFS(root);
function DFS(root){
if(!root) return [];
let visited = new Map(),
stack = [root];
console.log(visited)
while(stack.length){
let node = stack.pop()
visited.set(node,1);
// process(node);
// nodes = generate_related_nodes(node);
let nodes = node.children;
stack.push(...nodes);
}
}

广度优先
非递归
从根节点逐层访问下一层节点,在树的广度优先搜索里即层序遍历
需要队列维护,树中的节点先进先出,队列先放入根节点[root],然后队首出一个节点后,打印,再push他的子节点,如此实现横向打印

const root = document.querySelector('.wrapper');
console.log(root);
BFS(root);
function BFS(root){
if(!root) return [];
let visited = new Map(),
queue = [root];
while(queue.length){
let node = queue.shift();
visited.set(node,1);
let nodes = node.children;
queue.push(...nodes);
}
console.log(visited);
}

应用
getElementById模拟
递归
const root = document.querySelector('.wrapper');
// 在root节点找id为xx的节点
function getElementById(node, targetId) {
if (!node) return null;
if (node.id === targetId) return node;
for (let curNode of node.children) {
let target = getElementById(curNode, targetId);
if (target) return target;
}
return null;
}
非递归
function getElementById(node, targetId) {
if (!node) return null;
let stack = [node];
while(stack.length){
let curnode = stack.pop();
if(curnode.id === targetId) return curnode;
stack.push(...curnode.children);
}
return null;
}
querySelector模拟
querySelector(“.mls-info > div .copyright-content”) 有个空格表示父子关系
思路:
1、解析选择器,序列化关键词 (从右到左匹配)
//把selector解析为
var selectors = [
// div .copyright-content 后代关系descendant
{relation: "descendant", matchType: "class", value: "copyright-content"},
// .mls-info > div 子代关系child
{relation: "child", matchType: "tag", value: "div"},
// .mls-info 顶级选择器
{relation: "subSelector", matchType: "class", value: "mls-info"}];
matchType的作用就在于用来比较当前选择器是否match
function match(node, selector){
if(node === document) return false;
switch(selector.matchType){
//如果是类选择器
case "class":
return node.className.trim().split(/ +/).indexOf(selector.value) >= 0;
//如果是标签选择器
case "tag":
return node.tagName.toLowerCase() === selector.value.toLowerCase();
default:
throw "unknown selector match type";
}
}
根据节点之间的关系,确定下一个遍历的范围
- 后代关系:从当前节点往上找,从父节点,再找父节点的父节点,一直往上直到匹配 or 遇到document
- 子代关系:直接比较父节点
function nextTarget(node, selector){
if(!node || node === document) return null;
switch(selector.relation){
case "descendant":
return {node: node.parentNode, hasNext: true};
case "child":
return {node: node.parentNode, hasNext: false};
case "sibling":
return {node: node.previousSibling, hasNext: true};
default:
throw "unknown selector relation type";
//hasNext表示当前选择器relation是否允许继续找下一个节点
}
总函数:
// .mls-info > div .copyright-content
var selectors = [
// div .copyright-content 后代关系descendant
{relation: "descendant", matchType: "class", value: "copyright-content"},
// .mls-info > div 子代关系child
{relation: "child", matchType: "tag", value: "div"},
// .mls-info 顶级选择器
{relation: "subSelector", matchType: "class", value: "mls-info"}
];
function querySelector(node, selectors) {
while (node) {
let currentNode = node
if (!match(node, selectors[0])) {
node = nextElement(currentNode);
continue;
}
let next = null;
for (let i =0; i<selectors.length; i++) {
let isMatch = false;
do {
next = nextTarget(node, selectors[i]);
node = next.node;
// 如果没有相关节点,当前node匹配失败
if (!node) break;
if (match(node, selectors[i+1])) {
isMatch = true;
break;
}
}while (next.hasNext);
if (!isMatch) break;
}
// 已经把所有选择器匹配完,且都成功,说明匹配成功
if (match && i === selectors.length -1) {
return currentNode;
}
node = nextElement(currentNode);
}
return null;
}
获取元素绝对位置
计算元素左上角相对于整张网页的坐标
function getElementPosition(e) {
var x = 0;
var y = 0;
while (e !== null) {
x += e.offsetLeft;
y += e.offsetTop;
e = e.offsetParent;
}
return {x: x, y: y};
}
插入li优化
DocumentFragment
<!--
1、插入100个li到body
2、破解前端面试(80% 应聘者不及格系列):从 DOM 说起
https://juejin.im/post/58f558efac502e006c3e5c97
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul id="ulcontainer"></ul>
<script>
// 原始版
for (var i = 0; i < 100; i++) {
document.getElementById('#ulcontainer').innerHTML += ('<li>' + (i + 1) + '</li>');
}
// 进阶版
var html = [];
for (var i = 0; i < 100; i++) {
html.push('<li>' + (i + 1) + '</li>');
}
document.getElementById('#ulcontainer').innerHTML = html.join('');
/**
* 可以考虑的优化的点
* 1、容错能力
* 2、最小作用域原则
*/
var docfrag = document.createDocumentFragment();
new Array(100).fill(1).forEach(function (e, index) {
var li = document.createElement('li');
li.textContent = index;
docfrag.appendChild(li);
});
document.getElementById('#ulcontainer').appendChild(docfrag);
</script>
</body>
</html>
