So how many times have you done the following:


var elm = $('.selector');
if ( elm.hasClass('selectedElement') ) {
elm.removeClass('abc');
} else {
elm.addClass('abc');
}

One alternative to the above example is to use jQuery’s toggleClass() method, but toggleClass does exactly that, toggles the class without a way for us to know the current state.

So now to the point of this post, accessing a jQuery function using associative array notation. Here’s an example of a typical jQuery operation:


// Call addClass('abc') on all divs
$('div').addClass('abc');

Here’s the same jQuery operation using associative array notation.

// Call addClass('abc') on all divs using associative array notation
$('div')['addClass']('abc');

Now the refactored example from the beginning of this post:

var elm = $('.selector');
elm[ ( elm.hasClass('selectedElement') ? 'remove' : 'add' ) + 'Class' ]('abc');

Here’s some additional links on JavaScript objects as Associative Arrays: