View Full Version : changing element styles in real time

02-06-2003, 11:16 PM
I'm using sliders to change text colour dynamically; at the moment, I'm doing it by iterating through the getElementsByTagName collection; like

paraAry = document.getElementsByTagName("p");
paraAry[j].style.color = "rgb("+bodyColor[0]+","+bodyColor[1]+","+bodyColor[2]+")";
paraAry[j].style.borderColor = "rgb("+textColor[0]+","+textColor[1]+","+textColor[2]+")";
paraAry[j].style.backgroundColor = "rgb("+textColor[0]+","+textColor[1]+","+textColor[2]+")";

But blatantly it's well inefficient; is there a better way to achieve this - like just a single property I can change to make all elements of a given name change.

02-07-2003, 09:27 PM
Yes, and it is called DOM2 CSS. :)

Let's say you have a selector like so:

.myP {
/* styles for special paragraph elements of whatever */

And also assume that it is in the very first stylesheet on the page (you could always adjust the index number of course appropriately):

var rules = document.styleSheets.item(0).cssRules;
var pClass;
for (var i = 0; i < rules.length; i++) {
if (rules.item(i).type == CSSRule.STYLE_RULE && rules.item(i).selectorText == '.myP') {
pClass = rules.item(i);

Now, you can just go like:

pClass.style.backgroundColor = 'red';

and it will dynamically modify the style rule, which in turn affects all elements which inherit from it.

02-07-2003, 09:29 PM
And as an added bonus, IE supports something very similar to this. Like, instead of .cssRules, I think it is just .rules... and other minor discrepancies like that - but the same idea can still be done. Just browser around MSDN for the particular differences...

02-07-2003, 11:49 PM
That's ideal, thank you :thumbsup: