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 wan开发者_StackOverflow中文版t to use toggle function as it mess up on table.
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')
.
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();
精彩评论