kratz
kratz

Reputation: 576

Get class value of element having multiple classes assigned using jquery

I need to add and delete class on an element having multiple classes:

This is the html:

<div class="heading"> more html code here </div>

I want to add class and get value of the added class. Can I do this? If not, how can a new class be added or removed?

 if ($(".heading").attr('class') == 'hidden') then $(".heading").removeClass('hidden');
 else $(".heading").addClass('hidden');

Basically what I'm going to do is to toggle hide/show. I don't want to use toggle function as it mess up on table.

Upvotes: 1

Views: 6454

Answers (2)

EndangeredMassa
EndangeredMassa

Reputation: 17528

If the class isn't being used for things other than hiding and showing the element, you could just use jQuery's toggle method for showing and hiding elements.

$('.heading').toggle();

Upvotes: 1

No Surprises
No Surprises

Reputation: 4901

Did you know about toggleClass()?

$('.heading').toggleClass('hidden');

That should allow you to do what you're trying to do without even needing to know what the current class is. In general, if you want to check for a specific class on an element that might have multiple classes, use hasClass() instead of attr('class').

Upvotes: 5

Related Questions