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?

1
  • Side note: never use reserved keywords like class Commented Jul 26, 2016 at 12:38

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

You are right, I am not wrote it and test it, just type here. I will fix it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.