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
720

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?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
仅有的幸福

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
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!