Using jQuery, how do I toggle classA to classB on click going from:
<a class="switch" href="#">Switch</a>
<div class="classA"></div>
$('.switch').on('click', function(e){
$('.classA').removeClass('classA').addClass('classB');
e.preventDefault();
};
How do I toggle the class, instead of just replacing it like I'm doing here?
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.
Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.
To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.
JavaScript Toggle Class Multiple Elements You can also toggle class on multiple element at once. For this target multiple elements and use the toggle() method. To toggle a class on multiple elements select those elements and apply the toggle method on each element to handle their corresponding class.
jQuery has a toggleClass function:
<button class="switch">Click me</button>
<div class="text-block collapsed pressed">some text</div>
<script>
$('.switch').on('click', function(e) {
$('.text-block').toggleClass("collapsed pressed"); //you can list several class names
e.preventDefault();
});
</script>
you can use toggleClass()
to toggle class it is really handy.
case:1
<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>
case:2
<div id='mydiv' class="class2"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class1"></div>
case:3
<div id='mydiv' class="class1 class2 class3"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class3"></div>
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