Skip to content Skip to sidebar Skip to footer

Use Javascript To Get The Style Of An Element From An External Css File

I have a html like this:

Solution 1:

This would work for standards compliant browsers (not IE - currentStyle/runtimeStyle).

<body><divid="test">Testing</div><scripttype="text/javascript">window.onload = function() {
            alert(window.getComputedStyle(document.getElementById('test'),null).getPropertyValue('display'));
        }
    </script></body>

Solution 2:

Since display is not set directly as a style property, you won't get that using the above code. You have to get the computed value.

You can refer this page, Get styles

To get the value

var displayValue = getStyle("test", "display");

functiongetStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    elseif (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

Solution 3:

The CSS won't be loaded yet. Wrap your JavaScript in an "on-ready" event.

<body onload="alert(document.getElementById('test').style.display);">

Does that work for you?

Post a Comment for "Use Javascript To Get The Style Of An Element From An External Css File"