Manually Traverse a DOM Tree Using jQuery | James Wiseman

本文介绍了一种使用jQuery手动遍历DOM树的方法,目的是找出DOM树的最大深度,即最深层次的嵌套元素级别。通过递归函数实现这一目标,避免使用全局变量,使解决方案更加简洁且易于维护。

Manually Traverse a DOM Tree Using jQuery | James Wiseman

Example DOM Tree
Image via Wikipedia

jQuery does a wonderful job of traversing the DOM tree, so you might ask why you would like to do this yourself?
I recently encountered a requirement to count the maximum ‘depth’ of a DOM tree. I.e. find the level of the deepest nested element. So, I managed to knock this up in a few minutes:

  1. function Recurse($item, depth) {  
  2.     $item.each(function() {  
  3.         depth.count++;  
  4.         if (depth.count > depth.max) {  
  5.             depth.max = depth.count;  
  6.         }  
  7.         Recurse($(this).children(), depth);  
  8.     });  
  9.     depth.count--;  
  10.     return depth.max;  
  11. }  
  12.   
  13. $(document).ready(function() {  
  14.     alert(Recurse($("body"), { count: 0, max:0 }));  
  15. }  
function Recurse($item, depth) {
    $item.each(function() {
        depth.count++;
        if (depth.count > depth.max) {
            depth.max = depth.count;
        }
        Recurse($(this).children(), depth);
    });
    depth.count--;
    return depth.max;
}

$(document).ready(function() {
    alert(Recurse($("body"), { count: 0, max:0 }));
}

A few points to note about this

  • depth is an object with two members, count and max. We want to keep a count of the current and maximum depth, but want to avoid global variables (it’s better practice, and makes the solution more self-contained).
  • JavaScript doesn’t allow us to pass variables by reference. Using the variables within the passed depth object means we can pass values to lower levels of recursion.
  • We must pass an object in our first call. Technically the function can be improved by including a check for this.
  • The function returns depth.max. Although the return value doesn’t matter when the function is called recursively, its useful for passing our intended value out to the original calling function.

You can test this out on JsFiddle: http://jsfiddle.net/RqHzf/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值