jQuery as an Associative Array – Dynamically calling jQuery functions
So how many times have you done the following:
1 2 3 4 5 6 | 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:
1 2 | // Call addClass('abc') on all divs $('div').addClass('abc'); |
Here’s the same jQuery operation using associative array notation.
1 2 | // Call addClass('abc') on all divs using associative array notation $('div')['addClass']('abc'); |
Now the refactored example from the beginning of this post:
1 2 | var elm = $('.selector'); elm[ ( elm.hasClass('selectedElement') ? 'remove' : 'add' ) + 'Class' ]('abc'); |
Here’s some additional links on JavaScript objects as Associative Arrays: