Something that bugs me, especially when I’m in the depths of a nasty-looking jQuery chain, is the fact that there’s no way to reference the last selection, that is, without explicitly assigning it to a variable.

Look at the following code:

$( '#something' ).width( this.parent().innerWidth() ); /* NOT POSSIBLE */

This is what I’d really love to be able to do ($('#something') is assigned to this in the background). But, unfortunately, there’s no way to change the value of this (because it’s immutable); plus jQuery provides us with no way to grapple the previous selection. So, unless I want to mess around with functions as setters there’s really only two ways of doing what I want:

// #1 (BAD PRACTICE - selecting twice)
$( '#something' ).width( $('#something').parent().innerWidth() );
 
// #2
var something = $('#something');
something.width( something.parent().innerWidth() );

So now we’re left with only one acceptable way of doing this; assigning $('#something') to a variable and then referencing that variable from that point onwards.

I accept that this is the “best practice” but, to be honest, I really hate it… Just looking at it; it seems unnecessary. And I don’t want to mess around with functions as setters because that just makes the code even more bloated. Instead, I’d much rather have a property under the jQuery namespace that will always be referencing the last selection. Something like this:

$( '#something' ).width( $._this.parent().innerWidth() );
/* $('#something') === $._this */

And as the code progresses, $._this is re-assigned continually; always reflecting the previous selection.

Maybe, in the future, the jQuery team will choose to implement something like this, but, for now, it’s possible using the following “hack”:

(function(_jQueryInit){
 
    jQuery.fn.init = function(selector, context) {
        return (jQuery._this = new _jQueryInit(selector, context));
    };
 
})(jQuery.fn.init);

NOTE: This is not the same as jQuery(something).prevObject.

I know its usefulness may not be immediately apparent to all of you; and I don’t blame you if you don’t find this technique appealing, but, before you make your decision, consider that its usage is quite specific and I think you’ll only really understand its appeal when you’ve encountered a situation that requires it.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!