3

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?

Community
  • 1
  • 1
vaso123
  • 12,347
  • 4
  • 34
  • 64

2 Answers2

6

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

You did it correct in general. But your variable is not named $id, it is target. And class is a registered name in javascript, so you can't use it.

The method can be select as a property of $().

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

$(target)[method](myClass);
eisbehr
  • 12,243
  • 7
  • 38
  • 63