Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery get and set CSS classes

jQuery - Get and Set CSS Classes


With jQuery, it is easy to manipulate CSS elements.


jQuery CSS manipulation

jQuery has several methods for CSS manipulation. We will learn the following:


Sample stylesheet

The following stylesheet is used for all examples on this page:

.important

{

font-weight:

bold

;

font-size:

xx-large

;

}

.blue

{

color:

blue

;

}


jQuery addClass() method

The following example shows how to add a class attribute to different elements. Of course, when adding classes you can also select multiple elements:

Example

$

(

"

button

"

)

.

click

(

function

(

)

{

$

(

"

h1,h2,p

"

)

.

addClass

(

"

blue

"

)

; $

(

"

div

"

)

.

addClass

(

"

important

"

)

;

}

)

;

Try it »

You can also specify multiple classes in the addClass() method:

Example

$

(

"

button

"

)

.

click

(

function

(

)

{

$

(

"

body div:first

"

)

.

addClass

(

"

important blue

"

)

;

}

)

;

Try it »


jQuery removeClass() method

The following example shows how to remove a specified class attribute from different elements:

Example

$

(

"

button

"

)

.

click

(

function

(

)

{

$

(

"

h1,h2,p

"

)

.

removeClass

(

"

blue

"

)

;

}

)

;

Try it »


jQuery toggleClass() method

The following example shows how to use the jQuery toggleClass() method. This method toggles adding/removing classes on the selected elements:

Example

$

(

"

button

"

)

.

click

(

function

(

)

{

$

(

"

h1,h2,p

"

)

.

toggleClass

(

"

blue

"

)

;

}

)

;

Try it »


jQuery css() method

We will cover this in the next chapter jQuery css() method.