
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between switchClass and toggleClass Methods in jQuery
The switchClass() is used to switch class from an element. Use it, to replace one class with another. Add jQuery UI library to the web page to use switchClass().
Example
You can try to run the following code to learn how to work with switch class −
<html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a").click(function(){ $("a.active").removeClass("active"); $(this).addClass("active"); }); }); </script> <style> .active { font-size: 22px; } </style> </head> <body> <a href="#" class="demo1">One</a> <a href="#" class="demo2">Two</a> <p>Click any of the link above and you can see the changes.</p> </body> </html>
Toggle Class
If you want to toggle between classes, then use the toggleClass(). This is to add or remove classes from the selected elements.
Example
You can try to run the following code to learn how to toggle class −
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1, p").toggleClass("blue"); }); }); </script> <style> .blue { color: blue; } </style> </head> <body> <h1>Heading 1</h1> <p>This is demo text.</p> <button>Toggle</button> </body> </html>
Advertisements