i specified a div with a ID of testBox:
<div id="testBox"></div>
and style it in the head section :
#testBox {
background: red;
width: 25px;
height: 25px;
left: 0;
top: 0;
}
then at the bottom of the body,i put the JS :
var box = document.getElementById("testBox");
console.log(box.style.left);
console.log(box.style.width);
use the FireBug in FireFox ,but it just tell me:
it’s an empty string….
But when i put the style infomation in the div tag like this:
<div id="testBox" style="background: red;width: 25px;height: 25px;"></div>
then the JS could do its work,retrieve all the information i want
so is this the only way to get the style information whit it all inline ,or i just miss something,after all i am just new to the JS and DOM ….
When you say
box.idwhat is returned to you is theidattribute of the box element as declared in your html.When you say
box.styleyou are accessing a javascript object also created based on your markup.Styling attributes that are not defined inline are not used when the dom-representation of the style attribute is created.
Here is an article which highlights this behaviour.
However, if you use a library like jQuery you can do
and this will give you your css value.
UPDATE:
Thanks to AVD for pointing me in the right direction:
Here is a method which uses his solution but adds support for IE < 9:
Here is a fiddle.