tags:

views:

888

answers:

2

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.

+2  A: 

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').

No Surprises
It solve half of the problem. The other problem is getting the value of the class to check if 'hidden' class is added. Note that when 'hidden' class id added, the div has two declared classes and checking it with .attr('class') won't work.if ($(".heading").attr('class') == 'hidden'); --> this won't work.I don't want to manipulate hidden class in css.
kratz
I overlook your last paragraph... thanks. It works.
kratz
You're welcome! Why not accept the answer?
No Surprises
+1  A: 

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();
EndangeredMassa
I'm interested to understand how to check the certain element(with multiple class declaration) has a particular class.
kratz