1

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';
    });
});
2
  • 3
    It's extremely easy to answer this question by looking at the jQuery documentation. Go to api.jquery.com and type 'class' into the search. The answer is the third item in the list. Commented Jun 19, 2011 at 18:22
  • possible duplicate of Swap class w/jQuery Commented Jun 19, 2011 at 18:41

1 Answer 1

9

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.