Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get width of div, which is written in CSS

I want width of a div element which is specified by developer. Means if you write $('body').width(), it will provide you width in px , whether you have specified it or not.

I need width of div specified in CSS/JavaScript but not which is calculated by jQuery (which was not actually specified but was inherited).

If not width is specified then I need to know.

like image 957
Johnny Avatar asked Oct 26 '12 11:10

Johnny


2 Answers

The code below will loop through all stylesheets as well as the matching element's style property. This function will return an array of widths.

function getCSSWidths( id ) {

    var stylesheets = document.styleSheets;
    var widths = [];
    var styleWidth;

    // loop through each stylesheet
    $.each( stylesheets, function( i, sheet ) {

        var len = ( sheet.rules.length || sheet.cssRules.length );
        var rules = sheet.rules || sheet.cssRules;

        // loop through rules
        for (var i=0; i < len; i++) {

            var rule = rules[i];

            // if width is specified in css add to widths array
            if (rule.selectorText.toLowerCase() == "#" + id.toLowerCase() ) {
                widths.push( rule.style.getPropertyValue("width"));
            }
        }
    });

    var el = document.getElementById( id );

    // get width specified in the html style attribute
    if( el && el.style && el.style.width ) {
        widths.push( el.style.width );
    }

    return widths;
}

getCSSWidths( "test" );

Fiddle here

There is one issue that I can see though as multiple selectors can be specified in the selectorText i.e.

#id1, #id2, .class1 {
    // properties
}

In these cases the id passed in as an argument will not match the selectorText property. Maybe someone can come up with a regex expression that will match the specified id :)

like image 197
Bruno Avatar answered Sep 18 '22 13:09

Bruno


<style type="text/css">
    .largeField {
        width: 65%;
    }
</style>
<script>
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var i=0; rules.length; i++) {
        var rule = rules[i];
        if (rule.selectorText.toLowerCase() == ".largefield") {
            alert(rule.style.getPropertyValue("width"));
        }
    }
</script>

Possibly duplicate with get CSS rule's percentage value in jQuery or Getting values of global stylesheet in jQuery

like image 28
Mihai Matei Avatar answered Sep 17 '22 13:09

Mihai Matei