Q:

How to optimize this simple jquery code?

I am trying to learn a bit about optimizing my jQuery code...
Is there a way to improve the code below so that the variable $selected is declared outside of the function, but still accessible, so that the DOM is not traversed every time?
Or is this code about as optimized as it could be?
Or... I suppose I may be misunderstanding how and when jquery DOM traversal happens.
$('#full-width-layout_c1_col-1-1_1').on(
    'mouseenter mouseleave click', 
    'a.project_open, a.song_open', 
    function(e) {
        var $selected = $(this).closest('tr').find('div');
        if (e.type == 'mouseenter') {
            $selected.addClass("hovered");
        }
        else if (e.type == 'mouseleave'){
            $selected.removeClass("hovered");
        }
        else if (e.type == 'click'){
            $selected.addClass('opened');
        }
    }
);

A:

Don't use jQuery.data() if you want every last bit of performance when storing arbitrary data in the DOM elements. That would perform much better:
var $selected = this.closestdiv;

if(!$selected) { // first time
    $selected = $(this).closest('tr').find('div');
    this.closestdiv = $selected;
}

From this simple benchmark http://jsperf.com/jquerydata/4 you can see how faster it is to store data directly on DOM rather then using jQuery.data(). On my machine using jQuery.data() is 97% slower than storing data directly. Again, fair word of warning - jQuery.data() has certain amount of overhead because it's trying to be smart about things and prevent potential memory leaks.

