Thursday, August 26, 2010

The .css() method

One of the coolest methods in jQuery is the .css method. This allows you to get a style property based on the selector. This is convenient because different browsers have different DOM implementations of a property, but the .css() method accounts for the different implementations and produces the same result no matter which term we use. For example:

.css('backgroundColor')

and

.css('background-color')

return the correct value for both regardless of the DOM implementation.

So, that is all good but what can we actually do with it? The example above simply selects the element but by passing an extra parameter we can actually set the property. An example would look like:

.css('background-color', '#FFFFFF')

We can also pass it a function as a parameter which is a function returning the value to set, or if you really want to unleash the power of this method you can simply pass a map (property-value pairs to set). An example of this would look something like this:

.css( {'background-color' : '#FFFFFF', 'color' : '#DDDDDD' } )

No comments:

Post a Comment