Reputation: 515
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 ....
Upvotes: 2
Views: 1139
Reputation: 3241
When you say box.id
what is returned to you is the id
attribute of the box element as declared in your html.
When you say box.style
you 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
$(function(){alert($("#textBox").css("width"));});
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:
var box = document.getElementById("testBox");
var style = window.getComputedStyle ? window.getComputedStyle(box) : box.currentStyle;
alert("Height : " + style["height"]);
alert("Width : " + style["width"]);
alert("Left : " + style["left"]);
Here is a fiddle.
Upvotes: 0
Reputation: 94645
You may try getComputedStyle(). It gives the final used values of all the CSS properties of an element.
var box = document.getElementById("testBox");
var style=window.getComputedStyle(box);
console.log("Height : " + style["height"]);
console.log("Width : " + style["width"]);
console.log("Left : " + style["left"]);
Upvotes: 1