Hulk
Hulk

Reputation: 34160

How to override a class using jquery

A jQuery CSS class sets the following:

 .newwidget { border: 1px solid #5a9ee9; background: #5a9ee9 url(t6.gif) 50% 50% repeat-x; color: #ffffff; font-weight: bold; text-transform: uppercase; padding:3px 3px 3px 10px; font-size:10px}

How can this class be overridden and a new class added so that I can put different styles in it? Maybe I have to remove before classes before adding them. How is this done?

Thanks

Upvotes: 12

Views: 28714

Answers (6)

CAOakley
CAOakley

Reputation: 1202

If you're looking to completely replace the existing classes on an element, you can use the .attr() method.

$('#elementId').attr('class', 'newClassName');

Any classes on elementId will be replaced.

Upvotes: 10

Tom Rossi
Tom Rossi

Reputation: 12066

I think it's worth noting that you can remove all the classes by leaving off the parameter from removeClass():

$('.newwidget').removeClass().addClass('newerwidget');

Upvotes: 17

x4tje
x4tje

Reputation: 1643

$(this).removeClass('oldClass').addClass('newClass');

Upvotes: 2

Aaron
Aaron

Reputation: 7098

jQuery defines addClass() and removeClass() for just this purpose:

$("#ElementId").removeClass('oldClassName').addClass('newClassName');

The two function do the obvious. Chain them like this to change the class all in one action.

If you would like to change all elements from 'oldClass' to 'newClass', you can use a selector like this:

$(".oldClassName").removeClass('oldClassName').addClass('newClassName');

Upvotes: 6

nickf
nickf

Reputation: 546015

You can to remove the old class and add a new one:

$myJQObject.removeClass('newwidget').addClass('newclass');

Upvotes: 4

tvanfosson
tvanfosson

Reputation: 532435

Use the class selector with addClass and removeClass.

$('.newwidget').removeClass('newwidget').addClass('newerwidget');

Upvotes: 18

Related Questions