Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access style properties on javascript objects which are using external style sheets?

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: 150px;
}

I then have this:

<div id="0" class="box" style="position: absolute; top: 20px; left: 20px;">

When I then try to access the width of the div:

alert(document.getElementById("0").style.width);

A blank alert box comes up. How can I access the width property which is defined in my style sheet?

NOTE: The div displays with the correct width.

like image 328
Jesse Gibbs Avatar asked Jul 28 '09 11:07

Jesse Gibbs


2 Answers

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

like image 75
aditya Avatar answered Oct 07 '22 23:10

aditya


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
like image 27
Daff Avatar answered Oct 07 '22 21:10

Daff