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

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

问题描述

不幸的是,我需要遍历页面的所有DOM元素,我想知道最有效的技术是什么.我可以自己对这些基准进行基准测试,如果有时间的话,也可以,但我希望有人已经经历过或有一些我未曾考虑过的选择.

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.

目前,我正在使用jQuery并执行以下操作:

Currently I'm using jQuery and doing this:

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

虽然有效,但似乎会导致客户端出现一些滞后.也可以使用更具体的jQuery上下文(如 $('body','*'))进行调整.在我看来,本机Javascript通常比jQuery快,我发现了这一点:

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.

推荐答案

您发布的Vanilla Javascript方式最快.它会比您发布的jQuery解决方案快(请参阅我对这个问题的评论).如果您没有在循环中删除或向DOM中添加任何内容,并且遍历的顺序无关紧要,则还可以通过反向迭代来稍微加快它的速度:

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天全站免登陆