jaredatch/Custom-Metaboxes-and-Fields-for-WordPress — Issue #75: Cache jQuery Selectors Where Possible
Author: GaryJones
Created: 2011-12-31 17:43:17+00:00
State: open

Take the following (anonymous) function:

```
function() {
formfield = $(this).attr('rel');
$('input#' + formfield).val('');
$('input#' + formfield + '_id').val('');
$(this).parent().remove();
return false;
}
```
In this case, there's 4 selectors being used, 2 of which are the same (`$(this)`). Where possible, these selectors should be cached, since trawling through the DOM can be expensive.

```
function() {
// Cache selector
var $this = $(this);

// Set value in an outer scope
formfield = $this.attr('rel');

// Wipe the value of ...
$('#' + formfield).val('');
$('#' + formfield + '_id').val('');

// Remove the ... from the DOM
$this.parent().remove();

return false;
}
```