深度优先算法最常用的是在DOM树查找中的实现
设计思路:修改nextElement的查找方式,如果有子节点,则下一个元素就是它的第一个子节点,否则,判断是否有相邻的节点,如果有返回它的相邻元素,如果即没有子节点也没有相邻节点,就返回父节点的下一个相邻节点,然后重新进入循环队列。
<div id="id-data-structure">
我是body
</div>
function getElementById(node, id) {
while(node) {
if (node.id === id) {
return node;
}
node = nextNode(node);
}
}
function nextNode(node) {
if (node.children.length) {
return node.children[0];
}
if (node.nextElementSibling) {
return node.nextElementSibling;
}
while (node.parentNode) {
if (node.parentNode.nextElementSibling) {
return node.parentNode.nextElementSibling;
}
}
return null;
}
getElementById(document, "id-data-structure");