lolka_bolka lolka_bolka - 4 months ago 19
jQuery Question

Call jQuery function from variable name directly

Maybe it is not possible what I want to do, I just hoping. If not, there is no problem and I will write a class. I just want to avoid that.

Of course, I tried to search for answers on net. I found something here on SO and on jQuery forum. Like this, or this, or this.

But what I want to do this in a different way:

I want to call it directly, and I do not want to use eval!

What I thought to do something like this

var target = '#id';
var method = 'removeClass';
var className = 'classToShow';

$(taget).method(className);


I am getting this:

TypeError: $(...).method is not a function
[Learn More]


So is there a way to do this?

Answer

As jQuery (and therefore the $ variable) refer to an object, you can use bracket notation, like this:

$(target)[method](className);

var target = '#id';
var method = 'removeClass';
var className = 'classToShow';
$(target)[method](className);
.classToShow {
  color: red; /* this colour will be removed */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id" class="classToShow">Foo bar</div>