JavaScript DOM深度遍歷(2種方法)和廣度遍歷
阿新 • • 發佈:2019-02-06
DOM深度優先遍歷
1. API方法creatNodeIterator(ele,whatToShow,filter,boolean)
引數介紹:
whatToShow
:待顯示的節點型別,值有
NodeFilter.SHOW_ALL
NodeFilter.SHOW_ELEMENT
NodeFilter.SHOW_ELEMENT
NodeFilter.SHOW_ATTRIBUTE
filter
表示過濾待顯示的節點boolean
表示實體擴充套件,在HTML
頁面沒用,為false
其內部包含nextNode(),previousNode()
程式碼舉例
var body = document .getElementsByTagName('body')[0];
var filter = function (node) {
return node.tagName.toLocaleLowerCase() === 'li' || node.tagName.toLocaleLowerCase() === 'p'? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
}
var iterator = document.createNodeIterator(body,NodeFilter.SHOW_ELEMENT,null ,false);
var node = iterator.nextNode();
while(node !== null){
console.log(node.tagName);
node = iterator.nextNode();
}
2. API方法creatNodeTreeWalker(ele,whatToShow,filter,boolean)
引數和creatNodeIterator
一樣,但包含的功能更多,可以直接跳到對應的節點:
parentNode()
firstChild()
lastChild()
nextSibling()
previousSibling()
程式碼舉例
var body = document.getElementsByTagName('body')[0];
var walker = document.createTreeWalker(body,NodeFilter.SHOW_ELEMENT,null,false);
var node = walker.firstChild();
node = walker.nextSibling();
while(node !== null){
console.log(node.tagName);
node = walker.nextNode();
}
3.遞迴方法實現
function deepFirstSearch (node) {
console.log(node.tagName);
if(node.children.length){
Array.from(node.children).forEach(function (el) {
deepFirstSearch (el);
})
}
}
DOM廣度優先遍歷
原理:先將node節點push進queue中,每次處理一個出隊的元素直到queue中無元素待處理,每次處理完一個節點後,將其子節點全部push進陣列queue中
function wideFirstSearch(node) {
var queue = [];
while(node){
console.log(node.tagName);
Array.from(node.children).forEach(function (el) {
queue.push(el);
});
node = queue.shift();
}
}