1

i was wondering things...

If i need to get the content or append an click function to an div, as the structure of the selectors it's something like that:

$('body #content #sidebar .modalwindow #global-content')

i want to target #global-content, the final id of the selectors. what its better? Just target it as $('#global-content') and do what i wanna or give to it all the path?

Wallysson Nunes
  • 760
  • 6
  • 16

4 Answers4

2

$('#global-content') is the best selector to use, altough maybe the whole selector will be executed the same way (if jQuery starts from right to left, which I'm not sure it does). ID should be unique and getElementById() is the fastest native browser method, so $('#global-content') is the fastest possible selector.

Keep in mind also, that when you are searching for something exactly 1 level lower in the DOM tree, you can put > in the selector. Example:

$('body .content') is equialent to $('body').find('.content')

$('body > .content') is equialent to $('body').children('.content')

The second one is faster.

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • $('body .content') is equialent to $('body').find('.content') $('body > .content') is equialent to $('body').children('.content') – Wallysson Nunes Aug 31 '11 at 20:20
2

You can experiment and try out your selectors here

aziz punjani
  • 25,586
  • 9
  • 47
  • 56
1

if you know the id of your element and if your id is really unique (as it should be). It is faster to call directly the id >> $('#global-content').

Thus, it is interpreted by jquery to one of the fastest selector getElementById() instead of filtering the DOM.

Note: I know jquery 1.5 and higher (maybe even since 1.4) were optimized to select by id even if the jquery code was adding too much information but that's not the best way to rely on the framework to correct a bad coding

JMax
  • 26,109
  • 12
  • 69
  • 88
1

a similar question was asked in

jQuery Selectors, efficiency

the answer is that

$('#global-content')

is faster

Community
  • 1
  • 1
dov.amir
  • 11,489
  • 7
  • 45
  • 51