I know I can set a CSS value through JavaScript such as:
document.getElementById(\'image_1\').style.top = \'100px\';
But, can I
As a matter of safety, you may wish to check that the element exists before you attempt to read from it. If it doesn't exist, your code will throw an exception, which will stop execution on the rest of your JavaScript and potentially display an error message to the user -- not good. You want to be able to fail gracefully.
var height, width, top, margin, item;
item = document.getElementById( "image_1" );
if( item ) {
height = item.style.height;
width = item.style.width;
top = item.style.top;
margin = item.style.margin;
} else {
// Fail gracefully here
}
Cross-browser solution to checking CSS values without DOM manipulation:
function get_style_rule_value(selector, style)
{
for (var i = 0; i < document.styleSheets.length; i++)
{
var mysheet = document.styleSheets[i];
var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
for (var j = 0; j < myrules.length; j++)
{
if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector)
{
return myrules[j].style[style];
}
}
}
};
Usage:
get_style_rule_value('.chart-color', 'backgroundColor')
Sanitized version (forces selector input to lowercase, and allows for use case without leading ".")
function get_style_rule_value(selector, style)
{
var selector_compare=selector.toLowerCase();
var selector_compare2= selector_compare.substr(0,1)==='.' ? selector_compare.substr(1) : '.'+selector_compare;
for (var i = 0; i < document.styleSheets.length; i++)
{
var mysheet = document.styleSheets[i];
var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
for (var j = 0; j < myrules.length; j++)
{
if (myrules[j].selectorText)
{
var check = myrules[j].selectorText.toLowerCase();
switch (check)
{
case selector_compare :
case selector_compare2 : return myrules[j].style[style];
}
}
}
}
}
If you're into libraries, why not MyLibrary and getStyle.
The jQuery css method is misnamed, CSS is just one way of setting styles and doesn't necessarily represent the actual values of an element's style properties.