Use a parameter as jQuery method

I'm trying to use a parameter to define a jQuery method like:

function first(parameter1, parameter2, parameter3) {
   $(parameter1).parameter2(parameter3);
}

I want to call it with onclick="first('#mydiv', 'fadeIn', 'slow');" but it doesn't work. The console says:

(...).parameter2 is not a function

Answers 1

  • Firstly your jQuery object is missing the $. Secondly, to access a property of an object you need to use bracket notation. Try this:

    function first(parameter1, parameter2, parameter3) {
       $(parameter1)[parameter2](parameter3);
    }
    

    Working example


Related Articles