Web Development with jQuery®

(Elliott) #1

(^166) ❘ CHAPTER 6 CSS
Note that because you are accessing the property through JavaScript as a string, you have the option
of either using camelCase or specifying the property name with a hyphen, as it is done in a style
sheet. This is also valid:
var backgroundColor = $('div').css('background-color');
After you make a selection, you call the css() method chained to the selection with the property
that you want the value for. The snippet of code here returns the backgroundColor for the fi rst


element of the selection, so if there are fi ve
elements present in a document, the preceding code
would return the background-color for the fi rst one.
If you want to retrieve multiple properties, you specify an array of properties to retrieve, and an
object of property/value pairs are retrieved from the element.
var properties = $('div').css([
'background-color',
'color',
'padding',
'box-shadow'
]);
The preceding example returns an object containing the specifi ed properties. Remember, you can
always dump the content of a variable to the JavaScript console using the console.log() method, if
you want to know what value a variable contains.
If you want to set the value of a single property, that’s done like this:
$('div').css('background-color', 'lightblue');
In the preceding example, the background-color of all
elements in the document is set to
lightblue.
Setting multiple properties for multiple elements can be done like this:
$('div').css({
backgroundColor : 'lightblue',
border : '1px solid lightgrey',
padding : '5px'
});
Or this:
$('div').css({
'background-color' : 'lightblue',
border : '1px solid lightgrey',
padding : '5px'
});
An object literal with key, value pairs is passed to the css() method. In the preceding example, the
background-color is set to lightblue, the border is set to 1px solid lightgrey, and the padding is set
to 5px for all the
elements in the document. You can use hyphenated property names like this
as well, but you must place quotes around any property names that contain hyphens.
http://www.it-ebooks.info