Off the Ridge code

Off the Ridge Code Newsletter

Search

jQuery – Pro Tip #2

Published January 23, 2015 in jQuery - 1Comments

jQuery – Pro Tip #2 – selector caching!

instead of repeating the selector and hence (re)traveling the DOM:

function doWork(){
    $(‘#divTag’).addClass(“has-error”);
    $(‘#divTag’).slideUp();
}

cache the selector – caching it outside the method allows for reuse in multiple methods.
var someDivTag = $(‘#divTag’); 
function doWork(){
   someDivTag.addClass(“has-error”);
    someDivTag.slideUp();
}

and finally chain it:
function doWork(){
   someDivTag.addClass(“has-error”).slideUp();
}
  • http://businessfirstfamily.com source

    In the beginning, I thought your headline was misleading, but you actually delivered. Nice job.