Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing ClassName in jQuery

I know we can do many things like changing the current styles of an element, or changing its text etc. But, how can we change the name of the class using jQuery?

For example, the following CSS file has two different styles:

.roundedCorners {
  /* code for roundedCorners */
}

.NotSoRoundedCorners {
  /* code for NotSoRoundedCorners */
}

And the button looks like:

<input type="submit" class="NotSoRoundedCorners" value="Turn me on!" />

I know we can directly change its styles with a simple jQuery snip like this:

$('.closer').css({'visibility': 'hidden'}, 1000); // ETC.

But, what if there are many styles to change for the one element. Why not just have 2 style definitions in the CSS file, and when we need to change the style, just change the Class name of the element to the other style?


2 Answers

You should invoke jQuery's .toggleClass()help method.

Using that, you can explicitly remove and add a class to a node, leaving other classes untouched.

$('.closer').toggleClass('roundedCorners NotSoRoundedCornders');

Many guys here suggested to use .attr(), but that would replace the whole className attribute and therefore would overwrite/remove any given css class. I don't think thats the way to go.

like image 105
jAndy Avatar answered Apr 19 '26 12:04

jAndy


Yes. By using the attr method.

$('.NotSoRoundedCorners').attr('class', 'RoundedCorners');
like image 26
Decko Avatar answered Apr 19 '26 12:04

Decko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!