编写页面辅助
// 实例化 TreeWalker 对象 let walker = document.createTreeWalker( document.documentElement, NodeFilter.SHOW_ELEMENT ); // 遍历 let node = walker.nextNode(); while (node !== null) { node.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16); node = walker.nextNode(); }
获取页面所有节点
const treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode(node) { return NodeFilter.FILTER_ACCEPT; } } ); const nodeList = []; let currentNode = treeWalker.currentNode; while(currentNode) { nodeList.push(currentNode); currentNode = treeWalker.nextNode(); }