Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Aside from looping through an array that has each style property declared, is there any way to get a key/value output of all styling of a dom element?

My fallback is iterating through the keys listed on: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

is there any way to get a key/value output of all styling of a dom element?

Yes, but don't expect the exact handling of values (units etc.) to be the same cross-browser.

var styles= [];

// The DOM Level 2 CSS way
//
if ('getComputedStyle' in window) {
    var cs= getComputedStyle(element, '');
    if (cs.length!==0)
        for (var i= 0; i<cs.length; i++)
            styles.push([cs.item(i), cs.getPropertyValue(cs.item(i))]);

    // Opera workaround. Opera doesn't support `item`/`length`
    // on CSSStyleDeclaration.
    //
    else
        for (var k in cs)
            if (cs.hasOwnProperty(k))
                styles.push([k, cs[k]]);

// The IE way
//
} else if ('currentStyle' in element) {
    var cs= element.currentStyle;
    for (var k in cs)
        styles.push([k, cs[k]]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...