Wallysson Nunes
Wallysson Nunes

Reputation: 750

Performance in jQuery with selectors

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?

Upvotes: 1

Views: 120

Answers (4)

aziz punjani
aziz punjani

Reputation: 25796

You can experiment and try out your selectors here

Upvotes: 2

dov.amir
dov.amir

Reputation: 11627

a similar question was asked in

jQuery Selectors, efficiency

the answer is that

$('#global-content')

is faster

Upvotes: 1

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26749

$('#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.

Upvotes: 2

JMax
JMax

Reputation: 26611

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

Upvotes: 1

Related Questions