santa
santa

Reputation: 12512

Check if class is present w/jQuery

Is it possible to check if a certain class is present in an element and if yes, create a variable for my function?

<a href="#" id="clickMe"><span class="A open"></span>link</a>

For example if class open is present I will create a varialbe "close".

$(function ()
{
    $('#clickMe').click(function ()
    {
        // if "open"
        var myVar = 'close';
        // else 
        var myVar = 'open';
    });
});

Upvotes: 1

Views: 1184

Answers (1)

user578895
user578895

Reputation:

yes, hasClass will do it:

var isOpen = $(this).hasClass('open') ? 'close' : 'open';

Note that with your specific example, you'll need something closer to:

var isOpen = $(this).find('span').hasClass('open') ? 'close' : 'open';

since this in your callback will refer to the A and your open class is on the SPAN


jQuery also has a toggleClass method that may or may-not be what you're looking for:

$(this).toggleClass('open');

For reference: jQuery documentation It's usually pretty quick to find what you're looking for.

Upvotes: 9

Related Questions