jQuery

  • 26.1 Prefix jQuery object variables with a $.

    1. // bad
    2. const sidebar = $('.sidebar');
    3. // good
    4. const $sidebar = $('.sidebar');
    5. // good
    6. const $sidebarBtn = $('.sidebar-btn');

  • 26.2 Cache jQuery lookups.

    1. // bad
    2. function setSidebar() {
    3. $('.sidebar').hide();
    4. // ...
    5. $('.sidebar').css({
    6. 'background-color': 'pink',
    7. });
    8. }
    9. // good
    10. function setSidebar() {
    11. const $sidebar = $('.sidebar');
    12. $sidebar.hide();
    13. // ...
    14. $sidebar.css({
    15. 'background-color': 'pink',
    16. });
    17. }

  • 26.3 For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul'). jsPerf

  • 26.4 Use find with scoped jQuery object queries.

    1. // bad
    2. $('ul', '.sidebar').hide();
    3. // bad
    4. $('.sidebar').find('ul').hide();
    5. // good
    6. $('.sidebar ul').hide();
    7. // good
    8. $('.sidebar > ul').hide();
    9. // good
    10. $sidebar.find('ul').hide();