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.

1 comment:

  1. Hotel Casinos Near Mohegan Sun | Mapyro
    Find 양주 출장안마 the cheapest and quickest way to find and 울산광역 출장안마 book 서산 출장샵 a hotel 부산광역 출장마사지 near Mohegan 진주 출장안마 Sun Casino Find the best hotels in Uncasville, CT on Mapyro.

    ReplyDelete