I have an external style sheet with this in it:
.box {
padding-left:30px;
background-color: #BBFF88;
border-width: 0;
overflow: hidden;
width: 400px;
height:
I hope this is helpful:
function changecss(theClass,element,value) {
//Last Updated on June 23, 2009
//documentation for this script at
//http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
var cssRules;
var added = false;
for (var S = 0; S < document.styleSheets.length; S++){
if (document.styleSheets[S]['rules']) {
cssRules = 'rules';
} else if (document.styleSheets[S]['cssRules']) {
cssRules = 'cssRules';
} else {
//no rules found... browser unknown
}
for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
if(document.styleSheets[S][cssRules][R].style[element]){
document.styleSheets[S][cssRules][R].style[element] = value;
added=true;
break;
}
}
}
if(!added){
if(document.styleSheets[S].insertRule){
document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length);
} else if (document.styleSheets[S].addRule) {
document.styleSheets[S].addRule(theClass,element+': '+value+';');
}
}
}
}
It is taken from here.
The answers are mostly correct, but will do your head in when you try to use them as they depend on the rendering mode of the browser (aka strict/quirks mode, browser vender, etc) - the last answer is the best... use jquery.
You should use window.getComputedStyle
to get that value. I would recommend against using offsetWidth
or clientWidth
if you're looking for the CSS value because those return a width which includes padding and other calculations.
Using getComputedStyle
, your code would be:
var e = document.getElementById('0');
var w = document.defaultView.getComputedStyle(e,null).getPropertyValue("width");
The documentation for this is given at MDC : window.getComputedStyle
offsetWidth displays the actual width of your div:
alert(document.getElementById("0").offsetWidth);
This width can be different to what you have set in your css, though. The jQuery way would be (I really don't want to mention them all the time, but that's what all the libraries are there for):
$("#0").width(); // should return 400
$("#0").offsetWidth(); // should return 400 as well
$("#0").css("width"); // returns the string 400px