1. ホーム
  2. javascript

[解決済み] JavaScriptでCSSルールの値を読み取るには?

2022-07-29 21:07:32

質問

インライン スタイルで見られるような形式で、CSS ルールのすべての内容を文字列で返したいと思います。私は特定のルールに何が含まれているかを知ることなくこれを行うことができるようにしたいので、私はスタイル名によってそれらを引き出すことができません(例えば .style.width など)

CSSのことです。

.test {
    width:80px;
    height:50px;
    background-color:#808080;
}

ここまでのコード

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
            //this is where I can collect the style information, but how?
        }
    }
}
getStyle('.test')

どのように解決するのですか?

引用元 ここで を参考に、scunliffe さんの回答に基づいて作成しました。

function getStyle(className) {
    var cssText = "";
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var x = 0; x < classes.length; x++) {        
        if (classes[x].selectorText == className) {
            cssText += classes[x].cssText || classes[x].style.cssText;
        }         
    }
    return cssText;
}

alert(getStyle('.test'));