sam sam - 1 month ago 10
Javascript Question

How to read inline styling of an element?

I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element. I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

<div id="foo" style="width: 100px; height: 100px; background: green;"></div>


How can I determine that
width
,
height
, and
background
have been explicitly declared, inline?

As far as I can tell, the solution can work two ways. I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set. Like so:

var obj = document.getElementById('foo');
obj.hasInlineStyle('width'); //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles(); //returns array with values:
// 'width' 'height' and 'background'


I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles. One last thing, I have no control over the HTML source.

Thanks

Answer Source

Updated to work with IE

You could try something like this

function hasInlineStyle(obj, style) {
    var attrs = obj.getAttribute('style');
    if(attrs === null) return false;
    if(typeof attrs == 'object') attrs = attrs.cssText;
    var styles = attrs.split(';');
    for(var x = 0; x < styles.length; x++) {
        var attr = styles[x].split(':')[0].replace(/^\s+|\s+$/g,"").toLowerCase();
        if(attr == style) {
            return true;
        }
    }
    return false;
}

So if you have an element like this:

<span id='foo' style='color: #000; line-height:20px;'></span>

That also has a stylesheet like this:

#foo { background-color: #fff; }

The function would return...

var foo = document.getElementById('foo');
alert(hasInlineStyle(foo,'color')); // true
alert(hasInlineStyle(foo,'background-color')); // false