Skip to content

Instantly share code, notes, and snippets.

@ibrokemywp
Created November 22, 2014 14:25
Show Gist options
  • Save ibrokemywp/e1cfc48672f67bde444b to your computer and use it in GitHub Desktop.
Save ibrokemywp/e1cfc48672f67bde444b to your computer and use it in GitHub Desktop.
Store dom selections in a var for reuse
/**
* You've probably done this before. I know I have.
*/
var text = $( '#myid .select a > element' ).text();
newtext = doSomeStuff( text );
$( '#myid .select a > element' ).text( newtext );
$( '#myid .select a > element' ).addClass( 'someClass' );
$( '#myid .select a > element' ).fadeIn();
/**
* Now you've made jQuery go searching for the same
* DOM element 4 times. What a dick.
*
* Store that reference so you can reuse it. Here
* we're only asking jQuery to go find it once.
*/
var dom_element = $( '#myid .select a > element' );
var text = dom_element.text();
newtext = doSomeStuff( text );
dom_element.text( newtext );
dom_element.addClass( 'someClass' );
dom_element.fadeIn();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment