...

View Full Version : How to access CSS properties from JavaScript



timewinds
07-22-2002, 10:06 AM
I am working on a program that requires the use of certain CSS properties to be used inside a JavaScript file. I want to access the "background-color" property of div.Item (where Item is the class) inside a function. How do I do that ?
I tried document.classes.Item.backgroundColor but it throws an error when I open the html page.
Please help:confused:

glenngv
07-22-2002, 10:21 AM
for all IE:
document.all["IDofDIV"].style.backgroundColor

for IE5 & up and NS6.X:
document.getElementById("IDofDIV").style.backgroundColor

timewinds
07-22-2002, 12:21 PM
I want to access the property without any ID. Can I do that ?

The div.Item is defined in the CSS as follows:
div.Item
{
background-color: #00ff00;
}

Can I access this property of div.Item from JavaScript in any way?
:confused:

jkd
07-22-2002, 06:16 PM
Using the DOM2 Style and CSS specs:

Let's say the rule is contained in the very first stylesheet on the page:

var rules = document.styleSheets.item(0).cssRules;
for (var i = 0; i < rules.length; i++) {
if (rules.item(i).selectorText == 'div.Item') {
rules.item(i).style.backgroundColor = 'newcolor';
break;
}
}

That will work in any Gecko-based browser (NS6, NS7, Mozilla, Galeon, Beonex, and K-meleon), and no other browser because Gecko is the only browser to support DOM2 to this extent.

IE has some proprietary style stuff that I'll look into for you and post back in a bit.

timewinds
07-22-2002, 06:23 PM
Actually jkd, I wanted it for IE only.....it would be great if you can help me out. Thanks.

jkd
07-22-2002, 06:37 PM
Why would you *want* something IE-only when you can have it crossbrowser? :confused:

Anyway, after a bit of hunting, this should work crossbrowser:

var rules = document.styleSheets.item(0);
rules = rules.cssRules || rules.rules;
for (var i = 0; i < rules.length; i++) {
if (rules.item(0).selectorText == 'div.Item') {
rules.item(i).style.backgroundColor = 'newcolor';
break;
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum