Is it faster to traverse the DOM from a cached selector than to find an ID'd element in the DOM?

可紊 提交于 2019-12-22 10:29:54

问题


There are a lot of questions about whether or not finding an element is faster via class or id or some other selector. I'm not interested in that. I want to know if you have:

var link = $(this); //let's say you're in a click handler

Is it faster to find the container by doing

var container = link.closest('.container'); //assume container is .container

or

var container = $('#mycontainer'); //assume same element as above

I'm asking this question not just for the particular scenario above (ok, well, yes, for this scenario too) but for cached traversal vs. creating a fresh jQuery object that has an ID. I notice in a lot of my code I tend to do the former method (since it can lend itself to being more dynamic), but I was always curious if it was faster to do it the latter way.

Thanks


回答1:


I would think that, cached selector or not, it would be faster to use the id selector. The ID selector is pretty much a direct dictionary lookup vs the cached/closest combination which is like a dictionary lookup, followed by a tree traversal.

http://jsperf.com/traverse-from-cached-selector-vs-id-selector

The fastest lookup would be done with the native documentGetElementById function.

var container = $(document.getElementById('MyContainer'));


来源:https://stackoverflow.com/questions/10424975/is-it-faster-to-traverse-the-dom-from-a-cached-selector-than-to-find-an-idd-ele

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!