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 wh开发者_JAVA技巧at i wanna or give to it all the path?
$('#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.
You can experiment and try out your selectors here
a similar question was asked in
jQuery Selectors, efficiency
the answer is that
$('#global-content')
is faster
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
精彩评论