Accessing CSS properties with JavaScript

admin

Administrator
Staff member
I'm working on a dynamic positioning issue. It seems that I can't get access to any style information unless it is explicitly declared in a style attribute of the element in question. I wish to use CSS rules to determine the appearance of the element by adding a "class" attribute to the tag. I would then like to read and set the values of particular CSS properties for individual elements.

For example, if I have a style rule like:
.ox {width:100px;
height:20px;
position:absolute;
left:20px;
top:20px;}

And somewhere later in the document an element like this:

<div class="ox" id="x1">Menu Item</div>

Further suppose that I want to change the width of this div by adding 10px to the current value. I was hoping to do this in JavaScript like this:

document.getElementById("x1").style.width = parseInt(document.getElementById("x1").style.width) + 10 + "px";

The value I get for width is "undefined", so parseInt() returns a NaN.

If instead I included a style attribute in the element like this:

<div class="ox" id="x1" style="width:100px;"></div>

parseInt() will return "100", and widening the div is no problem.

Is there a way to access rule-defined properties from JavaScript?
 
Back
Top