lolka_bolka lolka_bolka - 1 year ago 58
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';


I am getting this:

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

So is there a way to do this?

Answer Source

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


var target = '#id';
var method = 'removeClass';
var className = 'classToShow';
.classToShow {
  color: red; /* this colour will be removed */
<script src=""></script>
<div id="id" class="classToShow">Foo bar</div>