Home  >  Q&A  >  body text

javascript - Traverse dom nodes, convert it into an array, and sort the deeper ones to the front. How to achieve this?

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?

高洛峰高洛峰2695 days ago752

reply all(1)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-26 10:53:49

    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
    }

    reply
    0
  • Cancelreply