3

I need to change values of css attributes of classes, i discovered that i can use document.styleSheets[i].rules and cssRules to access stylesheet data and modify the each attribute with the style property as described here: https://stackoverflow.com/a/324533/826472

is this a good idea or should i rather do a $(".class-name").style("attribute", "value") with jQuery.

the first solution seems slick but i'm not sure, i didn't see it that often (at all) and i don't see the changes in the inspector (only in the calculated pane)

treckstar
  • 1,956
  • 5
  • 21
  • 26
nici
  • 95
  • 1
  • 8

3 Answers3

3

I would say using jQuery is pretty good if you are able to use it. The example in your link looks like it is outputting the styles, not changing them.

$(".class-name").css("attribute", "value")

Is what you want.

treckstar
  • 1,956
  • 5
  • 21
  • 26
1
var someval = 144;
$('#id').css({'left':someval +'px'});
$('h3').css('color':'red');

Click here !

Use it. Love it.

It drops inline styles into your markup on the fly and just works. If you want to apply dynamic rules - this is certainly your best bet.

Additionally, a better practice may be to .addClass / .removeClass as it is more maintainable.

MNasir
  • 137
  • 7
Bosworth99
  • 4,206
  • 5
  • 37
  • 52
  • i need to change values directly (dynamically calculated) - predefined classes don't suffice – nici Feb 05 '13 at 17:03
  • Then use .css(). Seriously. I've used it *extensively* in many projects. A very solid solution, certainly better than trying to rewrite stylesheets on the fly. – Bosworth99 Feb 05 '13 at 17:04
  • i love .css() just a question in relation to globally setting a h3 or querying it and using .css() – nici Feb 05 '13 at 17:09
  • well - it depends on how many rules you need to set. Even assuming its "many" i still think managing it via .css is superior to trying to modify the stylesheet itself. – Bosworth99 Feb 05 '13 at 17:26
1

You will not be able to change existing CSS rules through jQuery. jQuery only affects inline styles of selected elements, so if you load new elements on the page after the fact, they will inherit styles from the original stylesheet.

If your goal is to edit existing stylesheets, your only choice is to use the CSS Object Model (e.g. cssRules, etc). Keep in mind that the Chrome inspector does not let you edit these CSS rules after you've programmatically defined them, it just shows them as read-only (though they do appear outside of the calculated pane).

You can use a lightweight library like css.js or JSS to help you out.

Vlad Magdalin
  • 1,692
  • 14
  • 17