<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<meta
name='viewport'
content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'
/>
<meta http-equiv='X-UA-Compatible' content='ie=edge' />
<title>Document</title>
</head>
<body>
<p>template</p>
<div id='box'>
<p>hello <b>world</b></p>
<img src='' alt='' />
<ul>
<li>a</li>
<li>b</li>
</ul>
</div>
<script>
function visitNode(n) {
if (n instanceof Comment) {
console.log('Comment node ---', n.textContent)
}
if (n instanceof Text) {
if (n.textContent?.trim() !== '') {
console.log('Text node ---', n.textContent)
}
}
if (n instanceof HTMLElement) {
console.log('Element node ---', `<${n.tagName.toLocaleLowerCase()}>`)
}
}
function depthFirstTraverse(root) {
visitNode(root)
if (root.childNodes.length) {
Array.from(root.childNodes).forEach(item => {
depthFirstTraverse(item)
})
}
}
function depthFirstTraverseByStack(root) {
const stack = []
stack.push(root)
while (stack.length > 0) {
const node = stack.pop()
visitNode(node)
if (node.childNodes.length) {
Array.from(node.childNodes)
.reverse()
.forEach(item => {
stack.push(item)
})
}
}
}
function breadthFirstTraverse(root) {
const queue = []
queue.push(root)
while (queue.length > 0) {
const node = queue.shift()
visitNode(node)
if (node.childNodes.length) {
Array.from(node.childNodes).forEach(item => {
queue.push(item)
})
}
}
}
</script>
</body>
</html>