Get CSS Value with JavaScript

  • Home / Blog / Get CSS Value…

Get CSS Value with JavaScript

The element styling property lets you know only the CSS properties that were specified in this element as inline (programmatically, or as defined in the element’s styling attribute) ۔

This is not so easy to do in the way of cross-browser, the element has its own way through the council style property, IE has its own way, and through other browsers, Dom Dom Level 2 is the standard way, through the documentation-default view. Bitcomputer style method.

There are differences in both methods, for example, the IE factor. Existing styling property expects you to access CSS property names consisting of two or more words in a camel case (such as max height, font size, background color, etc.), expect this property in a standard way Displays words separated by dashes (such as maximum height, font size, background color, etc.). ……

function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    // W3C standard way:
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hyphen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/-(w)/g, function(str, letter) {
            return letter.toUpperCase();
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^d+(em|pt|%|ex)?$/i.test(value)) { 
            return (function(value) {
                var oldLeft =, oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
       = value || 0;
                value = + "px";
       = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
        return value;

Important reference Stack overflow

Write a Comment

Your email address will not be published. Required fields are marked *