Last active
August 29, 2015 14:10
-
-
Save zbinlin/111e66a41b9fff1c3ded to your computer and use it in GitHub Desktop.
遍历 DOM 节点
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 深度优先 */ | |
function dom1(el, isBack) { | |
isBack || ++idx; | |
if (!el) { | |
return; | |
} | |
var next = isBack ? el.nextElementSibling : (el.firstElementChild || el.nextElementSibling); | |
return dom1(next ? next : el.parentNode, !next); | |
} | |
/* 广度优先 */ | |
function dom2(el, queue) { | |
queue || (++idx, queue = [el]); | |
var next = null; | |
if (!el) { | |
el = queue.shift(); | |
if (!el) { | |
return; | |
} | |
next = el.firstelementchild; | |
} else { | |
next = el.nextelementsibling; | |
} | |
next && queue.push(next) && ++idx; | |
return dom2(next, queue); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment