如何遍历 DOM 树? [英] How to iterate through a DOM tree?

查看:47
本文介绍了如何遍历 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 ?

编辑(我的代码太长了)

Edit (my code was too long)

推荐答案

此函数遍历 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天全站免登陆