How can I toggleClass and remove class from all other elements? Consider a div that contains a tags: html:
<div class="size">
<a href="">blahblah</a>
<a href="">blahblah</a>
</div>
jQuery:
$(".size a").click(function(){
$(this).toggleClass('checked');
if($(".size a").hasClass('checked')){
$(this).removeClass('checked');
}
})
I want to add class "cheched" to element and remove the class "ckeched" from other elements that have class "checked" . My code remove all classes. How can I add specific class and remove other element's class with click? Thanks in advance
jQuery toggleClass() Method The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.
toggleClass( function [, state ] ) A function returning one or more space-separated class names or an array of class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the state as arguments.
The toggle method makes an element visible or hidden, whichever is the opposite of what it is already. It's like using hide or show but you don't need to know which one to pick, it performs like the one that will make a difference. The toggleClass method does something similar to an element's class.
This will do it
$(".size a").click(function(){
$('.size a.checked').not(this).removeClass('checked');
$(this).toggleClass('checked');
})
Update
Alternatively you could do
$(".size").on('click','a', function(){
$(this).toggleClass('checked').siblings().removeClass('checked');
})
Only You need to Use it. :)
<script>
$(document).ready(function () {
$('.demo_class').click(function () {
$(this).toggleClass('active').siblings().removeClass('active');
});
});
</script>
So late but its my answer
$(".size").click(function(){
$('.size').removeClass('checked') //Clear all checked class on .size
$(this).addClass('checked') //Add checked class to current clicked .size
})
Its cleaner,powerfull and safe.
I'm assuming that you have a class 'size' that contains a number of elements of which only one should be able to have the class 'checked' at any one time.
$(".size a").click(function()
{
if($this).hasClass('checked')
{
$(".size a").removeClass('checked');
$(this).addClass('checked');
}
else
{
$(this).removeClass('checked');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With