How To Dynamically Select Part of a jQuery Call Chain

Updated, thanks to Simon Willison:

Say you’d like to pick part of your jQuery call chain dynamically - for example, to removeClass for many elements, but addClass to one special element. Here’s how you do it:


var myfunc = some_condition ? 'addClass' : 'removeClass';
$('#someid').html('something')[myfunc](’some_class’);

The first line selects the function name as a string. The second line calls the ‘html’ function (it could be any function; html is just the example in this case), followed by the function with the selected name (addClass or removeClass in this case).

You’d probably use this in the context of a loop, eg:


for (var i=0; i<10; i++) {
    var myfunc = some_condition ? 'addClass' : 'removeClass';
    $('#something'+ i).html('sample text ' + i)[myfunc]('selected');
}

3 Comments so far

  1. Simon Willison on May 8th, 2008

    Try this:

    var myfunc = some_condition ? ‘addClass’ : ‘removeClass’;
    $(’#someid’).html(’something’)[myfunc](’some_class’);

  2. Parand on May 8th, 2008

    Thanks Simon, will try that. That’s some funky syntax, but I guess I can see how that would work. Everything really is a hash…

  3. Mr Speaker on September 1st, 2008

    That is awesome… thanks guys!

Leave a Reply