最有效的方法来遍历所有的DOM元素? [英] most efficient way to iterate over all DOM elements?

查看:353
本文介绍了最有效的方法来遍历所有的DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,我需要迭代一个页面的所有DOM元素,我想知道最有效的技术是什么。我可以基准这些我自己,如果我有时间,但我希望有人已经经历过这个或有一些我没有考虑的选项。



目前我'使用jQuery并且这样做:

  $('body *')。each(function(){
var $ this = $(this);
// do stuff
});

虽然它的工作原理似乎在客户端造成一些滞后。它也可以调整一个更具体的jQuery上下文,如 $('body','*')
我发现本机javascript通常比jQuery和我发现这个。

  var items = document.getElementsByTagName(*); 
for(var i = 0; i< items.length; i ++){
// do stuff
}

我假设本机选项更快。想知道有没有其他的选择我没有考虑。也许是并行迭代子节点的递归选项。

解决方案

您发布的Vanilla Javascript方式是最快的。它将比您发布的jQuery解决方案更快(请参阅我对该问题的评论)。如果您在循环中没有删除DOM或添加任何内容,并且遍历顺序并不重要,您也可以通过反复迭代来加快速度:

  var items = startElem.getElementsByTagName(*); 
for(var i = items.length; i--;){
// do stuff
}

编辑:检查此基准测试,查看使用本机代码可以节省多少时间: http://jsben.ch/#/Ro9H6


Unfortunately I need to iterate over all the DOM elements of a page and i'm wondering what the most efficient technique is. I could probably benchmark these myself and might if I have the time but i'm hoping someone has already experienced this or has some options I hadn't considered.

currently i'm using jQuery and doing this:

$('body *').each(function(){                                                                                                                            
      var $this = $(this);                                                                                                                                
      //do stuff                                                                                                                                         
});

While it works, It seems to cause some lag on the client. It could also be tweaked with a more specific jQuery context like $('body', '*') It occurred to me that native javascript is usually faster than jQuery and I found this.

var items = document.getElementsByTagName("*");
    for (var i = 0; i < items.length; i++) {
        //do stuff
    }

I'm assuming the native option is faster. Wondering if there are other options I hadn't considered. Maybe a recursive option that iterates over child nodes in parallel.

解决方案

The Vanilla Javascript way you posted is the fastest. It will be faster than the jQuery solution you posted (See my comment on the question). If you're not removing or adding anything to the DOM in your loop and order of traversal doesn't matter, you can also speed it up ever so slightly by iterating in reverse:

var items = startElem.getElementsByTagName("*");
for (var i = items.length; i--;) {
    //do stuff
}

Edit: check this benchmark to see how much time you can save by using the native code: http://jsben.ch/#/Ro9H6

这篇关于最有效的方法来遍历所有的DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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