Prefix jQuery object variables with a $
.
// bad
var sidebar = $('.sidebar');
// good
var $sidebar = $('.sidebar');
Cache jQuery lookups.
// bad
function setSidebar() {
$('.sidebar').hide();
// ...stuff...
$('.sidebar').css({
'background-color': 'pink'
});
}
// good
function setSidebar() {
var $sidebar = $('.sidebar');
$sidebar.hide();
// ...stuff...
$sidebar.css({
'background-color': 'pink'
});
}
For DOM queries use Cascading $('.sidebar ul')
or parent > child $('.sidebar > ul')
. jsPerf
Use find
with scoped jQuery object queries.
// bad
$('ul', '.sidebar').hide();
// bad
$('.sidebar').find('ul').hide();
// good
$('.sidebar ul').hide();
// good
$('.sidebar > ul').hide();
// good
$sidebar.find('ul').hide();