Switch CSS Class Using jQuery

by Vincy. Last modified on July 6th, 2023.

In this post, we will switch the CSS class using jQuery. In a previous post, we saw how to switch CSS files based on the screen size to make the page responsive.

We have an example showing an image icon that is smaller on page load. And then, we switch the class attribute of this icon and change its size using jQuery.

View Demo

Switching Class Name using jQuery

This HTML form shows a smaller image icon with the class name small-icon.


<div class="image-content">
	<button id="switch">Switch Class</button> 
	<div  class="small-icon">
	  <img src="image.png" width="100%" />

This class attribute is changed on the button click event. jQuery switchClass function is used to change the class attribute. The script is,

  $(document).ready(function() {
      $(".small-icon").switchClass("small-icon", "large-icon", 500);
      $(".large-icon").switchClass("large-icon", "extra-large-icon", 500);
	  $(".extra-large-icon").switchClass("extra-large-icon", "small-icon", 500);

Switching the class names changes the icon size from smaller to more significant and to extra-larger size. The styles are,

  .image-content{width: 200px;border: #D2CCCC 1px solid;padding: 5px 40px;height: 280px;border-radius: 4px;box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.25);}
	#switch {padding: 10px 20px;margin: 15px 0px;border-radius: 4px;border: 0;background: #7A7B7B;color: #FFF;}

View DemoDownload

Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page