MitchCool1
MitchCool1

Reputation: 329

Jquery variable.addClass()

In a jquery function, I create a variable to hold the name of an image:

    tickNumber = $(this).data('imagenumber');
    tickName = "tick" + tickNumber; 

This generates "tick1", "tick2" etc.. I want to be able to change the class of the image with the name stored in that variable, I'm not sure how though. This is what I'm doing now:

        tickName.removeClass('visible');
        tickName.addClass('hidden')

That doesn't work, I'm not sure how I'm suppose to do it. Also, tickName is correct, doing this works:

        $(tick1).removeClass('visible');
        $(tick1).addClass('hidden');

But I need to use the variable's name instead.

Upvotes: 1

Views: 63

Answers (2)

Abhi
Abhi

Reputation: 4261

If tickName is used as ID then use it like

$("#" + tickName).removeClass('visible');
$("#" + tickName).addClass('hidden');

Else if it's a CLASS use:

$("." + tickName).removeClass('visible');
$("." + tickName).addClass('hidden');

Upvotes: 3

AmmarCSE
AmmarCSE

Reputation: 30557

Make tickName itself a jQuery object by wrapping in $(...)

$('.'+tickName).removeClass('visible');
$('.'+tickName).addClass('hidden');

and add a . to target classes

Upvotes: 2

Related Questions