Showing posts with label inline-styles. Show all posts
Showing posts with label inline-styles. Show all posts

Friday, 16 November 2012

How to get specific inline styles from Javascript?

At times we need to get specific inline styles from an HTML element. We can use jQuery to get that easily by specifying like $('#id').css('marginLeft');

But it will return the value of the margin-left inline style only in pixels(px), even if u specified in percentage(%) originally. To overcome that I've come across a solution using javascript using
document.getElementById('myDiv').style.cssText;
 
Code:
 
<script type="text/javascript">
function showStyles() {
    var s = document.getElementById('myDiv').style.cssText;
    var c = s.split(";");
    for ( var i = 0; i < c.length; i++ ) {
        var p = c[i].split(":");
        alert( p[0] + " is " + p[1] );
    }
}
</script> 

<div id="myDiv" style="height: 200px; width: 150px; margin-left: -10%;">
</div>
 
The above script will alert all the inline styles one by one exactly specified. If we
Want margin-left alone then use c[3] to output that. p[0] and p[1] specifies style 
attribute and value for the same.