Element + ID vs only ID in jquery?

2020-03-31 08:56发布

问题:

div#some_id will scan through all the divs throughout the DOM.

#some_id will pick up the ID directly from the DOM.

So which is faster? $('div#some_id') or $('#some_id')?

回答1:

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



回答2:

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.



回答3:

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