0

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')?

Jim Buck
  • 2,383
  • 23
  • 42
Ajay
  • 4,199
  • 4
  • 27
  • 47
  • possible duplicate of [Good ways to improve jQuery selector performance?](http://stackoverflow.com/questions/46214/good-ways-to-improve-jquery-selector-performance) – wizloc Sep 02 '15 at 14:19

3 Answers3

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.

Ulli
  • 500
  • 1
  • 7
  • 19
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

palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

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
0x_Anakin
  • 3,229
  • 5
  • 47
  • 86