views:

54

answers:

3

I haven't seen any docs saying jQuery can change any CSS definition such as changing

td { padding: 0.2em 1.2em }

to

td { padding: 0.32em 2em }

but either have to change a whole style sheet, or change class of each element, or change css of each element. Is changing the style definition possible?

A: 

Nope, it just doesn't work this way...not sure any better way to explain it than that :)

jQuery was designed to work on elements...if you're doing this for testing, Firebug of the Chrome console are options though.

Something you could do, is have a server-side generated stylesheet, for example how ThemeRoller does it, and jQuery (or vanilla JS) dynamically adds that <link> into your header, something like:

<link rel="stylesheet" href="myCSS.php?tdPad=.32|2" type="text/css" /> 

If it was the last link, it'd override the previously defined style...in fact this is exactly how ThemeRoller works.

Nick Craver
A: 
$('td').css({padding:'0.2em 1.2em'});

That what you mean ?

RobertPitt
+6  A: 

There is DOM access to stylesheets, but it's one of those things we tend to avoid because IE needs a load of compatibility cruft.

A better way would be typically be to trigger the change indirectly, using a simple class change on an ancestor:

td { padding: 0.2em 1.2em }
body.changed td { padding: 0.32em 2em }

Now just $('body').addClass('changed') and all the tds update.

If you really must frob the stylesheets:

var sheet= document.styleSheets[0];
var rules= 'cssRules' in sheet? sheet.cssRules : sheet.rules; // IE compatibility
rules[0].style.padding= '0.32em 2em';

This assumes that the td rule in question is the first rule in the first stylesheet. If not, you might have to go searching for it by iterating the rules looking for the right selectorText. Or just add a new rule to the end, overriding the old one:

if ('insertRule' in sheet)
    sheet.insertRule('td { padding: 0.32em 2em }', rules.length);
else // IE compatibility
    sheet.addRule('td', 'padding: 0.32em 2em', rules.length);

jQuery itself doesn't give you any special tools to access stylesheets, but it's possible there are plugins that might.

bobince