Element + ID vs only ID in jquery?

天涯浪子 提交于 2019-12-01 14:00:46

As ID are supposed to be unique in DOM, so div#some_id will be doing unnecessary scan on all DOM elements and #some_id will do a direct scan on it.

You can also see the result here: div-some-id-vs-some-id

See Optimize Selectors:

Beginning your selector with an ID is always best.

and

ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.

So the answer is: $('#some_id') should be faster.

I ran a simple test here in the console. It seems just using #id is faster as @Ulli said. Here is the test code:

var perf = performance;

var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
VM795:2 0.03399999695830047
undefined
var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
VM796:2 0.0329999893438071
undefined
var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
VM797:2 0.0329999893438071
undefined
var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
VM798:2 0.03500000457279384
undefined
var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
VM799:2 0.07000000914558768
undefined
var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
VM800:2 0.06600000779144466
undefined
var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
VM801:2 0.0680000230204314
undefined
var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
VM802:2 0.06799999391660094
undefined
var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
VM803:2 0.06799999391660094
undefined
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!