How to iterate through a DOM tree?

后端 未结 2 345
日久生厌
日久生厌 2021-01-28 15:55

I\'m working on a website which uses a tree structure made the following way : a list is created and if an element of this list is itself a list then it is append to the first l

相关标签:
2条回答
  • 2021-01-28 16:24

    If you think you will need several other functions on the tree, I suggest you to have a look on jsTree

    0 讨论(0)
  • 2021-01-28 16:29

    This function iterates through a DOM tree. You can pass it a callback that takes the parent and child element too:

    _SU3.treeIterate = function(parent, callback) {
       var children = _SU3.getChildren(parent);
       for (var i = 0; i < children.length; i++) {
          var child = children[i];
          callback(parent, child);
          _SU3.treeIterate(child, callback);
       }    
    };
    
    _SU3.getChildren = function(parent) {
    
      var children = new Array();
    
      var childNodes = parent.childNodes;
      if (childNodes == null) 
        return children;
    
      for (var i = 0; i < childNodes.length; i++) {
         var child = childNodes[i];
         if (child.tagName == "li" || child.tagName == "LI") {
            children.push(child);
         }
      }
      return children;
    };
    

    Note: in this example the getChildren() function only finds "li" items. Amend as necessary.

    0 讨论(0)
提交回复
热议问题