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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

You can experiment and try out your selectors here

Comments

1

a similar question was asked in

jQuery Selectors, efficiency

the answer is that

$('#global-content')

is faster

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.