如何迭代DOM树? [英] How to iterate through a DOM tree?

查看:83
本文介绍了如何迭代DOM树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个使用树结构的网站上进行了以下工作:创建一个列表,如果此列表的元素本身是一个列表,那么它将使用appendChild附加到第一个列表。大名单放在一个名为树的div中。
我想访问div'tree'的内容,并通过节点显示它们。

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 list using appendChild. The big list is put in a div named 'tree'. I would like to access the content of the div 'tree' and go through the nodes to display them.

我已经尝试了几种代码但是它不起作用,有人有什么想法如何做吗?

I've tried to code it several ways but it doesn't work, does someone has any idea how to do it ?

编辑(我的代码太长)

推荐答案

这个函数遍历一个DOM树。你可以传递一个需要父元素和子元素的回调:

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;
};

注意:在本示例中,getChildren()函数只找到li项。必要时进行修改。

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

这篇关于如何迭代DOM树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆