javascript - Traverse dom nodes, convert it into an array, and sort the deeper ones to the front. How to achieve this?
高洛峰2017-06-26 10:51:49
0
1
775
As the title says, start from a node and traverse downward until all nodes are traversed. Arrange the deepest nodes at the front and convert these nodes into an array. How to achieve this?
Traverse the children recursively, in order from bottom to top, left to right
function listNode (node) {
if (!(node instanceof Node)) {
throw new TypeError("parameter 1 is not of type 'Node'")
}
return Array.from(node.childNodes || [])
.reduce((cList, cNode) => cList.concat(listNode(cNode)), [])
.concat([node])
}
Note: The order from bottom to top and left to right does not necessarily mean the deepest layer is in front. You can use layer sequence traversal to record in reverse:
function listNode (rootNode) {
if (!(rootNode instanceof Node)) {
throw new TypeError("parameter 1 is not of type 'Node'")
}
var queue = [rootNode, null]
var levelNodes = []
var result = []
while (queue.length > 1) {
var node = queue.shift()
if (node === null) {
queue.push(null)
result = levelNodes.concat(result)
levelNodes = []
continue
}
levelNodes.push(node)
if (node.hasChildNodes()) {
queue = queue.concat(Array.from(node.childNodes))
}
}
if (levelNodes.length > 0) {
result = levelNodes.concat(result)
}
return result
}
Traverse the children recursively, in order from bottom to top, left to right
Note: The order from bottom to top and left to right does not necessarily mean the deepest layer is in front. You can use layer sequence traversal to record in reverse: