How to Edit a CSS Class Name With jQuery

This tutorial walks you through how to edit a CSS Class Name With jQuery.

In this tutorial we’re going to explore the process of editing a CSS class name using jQuery. Firstly let’s explore why you would want to do this, there are multiple uses but some include changing the styling of a box based on a button click or updating the layout of a page.

There are a few different ways to do this which we’ll explore below:

Firstly you can use toggleClass() this allows you to directly change the class using just this function.

Let’s say that you have a div class with the ID “div-identifier”. that div also has the class “initial-div-class”. We want to change that to “div-class-one”.

That would look like:

$(“#div-identifier”).toggleClass(‘div-identifier’ ‘initial-div-class’);

Another option is to use .attr()

Assuming we’re using the classes and ID mentioned above that would be:

$(”#div-identifier”).attr(‘.initial-div-class’, ‘div-class-one’);

Another option is to use .switchClass()
This goes a little further than the above as further functionality can be added. An example of it in use would be:

$(#div-identifier”).switchClass(‘.initial-div-class, ‘div-class-one’, 3000, ‘linear”);

This changes the classes on click but also adds a transition in the form of the ‘linear’ ‘easing’.

So let’s say you want this to occur on a button click it would look something like:

$(“button-name”).click(function() {

$(“#div-identifier”).toggleClass(‘div-identifier’ ‘initial-div-class’);

});

Further reading:

Adding jQuery to a WordPress website

We hope this provides you with an idea of getting started with editing a CSS class using jQuery. We’d appreciate a share or any comments if you found this useful, thanks!

Tech Typed
Tech Typed
Articles: 186

Leave a Reply

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