Tech and Media Labs
This site uses cookies to improve the user experience.

jQuery & CSS

Jakob Jenkov
Last update: 2014-09-17

With the JQuery CSS features you can manipulate the HTML element's CSS attributes and classes, and you can select HTML elements in the document based on their CSS class. In this text I will dive a bit deeper into how you do that, and explore what you can use that to achieve.

Accessing CSS Attributes With jQuery

You can both read and change the CSS properties of HTML elements using JQuery.

Reading CSS Properties

You read the CSS property of an element using the .css() method, like this:

var backgroundColor = $("#theElement").css('background-color');

Changing CSS Properties

You can change the CSS property of an HTML element with jQuery like this:

$("#theElement").css('background-color', '#00ff00');

Notice the extra parameter passed to the css() method, the '#00ff00' value. This is the value to set the CSS background-color property to.

jQuery can also change multiple CSS properties in a single call, by putting them all into a JavaScript object. Here is how that looks:

    'background-color' : '#00ff00',
    'border'           : '1px solid #000000'

Accessing CSS Classes With jQuery

JQuery's CSS manipulation is not limited to CSS properties. You can also change the CSS class of an HTML element using JQuery. CSS classes are defined in a CSS stylesheet, or in a <style> element.

You add a CSS class to an HTML element with jQuery like this:


This jQuery example selects the element with the id theElement, and then adds the CSS class theClass to it.

You can add multiple classes by separating the class names with a space, in the method parameter. Like this:

$("#theElement").addClass('theClass class2 class3');

You can also toggle a CSS class with jQuery using the toggleClass() method. Toggling a CSS class means adding the class if it is not already there, or removing the class if it is. Here is an example:


You can also toggle multiple classes by separating each of the class names by a space, like this:

$("#theElement").toggleClass('theClass class2 class3');

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC