😺
Vanilla JavaScriptで要素に複数のCSSを設定する方法【疑似要素にも可能】
よく見るstyle指定方法
element.style.color = "red";
element.style.fontSize = "20px";
Object.assign()
Object.assign(element.style, {
fontSize: "50px",
color: "red",
textAlign: "center",
});
setAttribute()
element.setAttribute('style','color:red','font-size:14px');
CssText
element.style.cssText = `
width: 80%;
height: 400px;
background-color: blue;
`;
CSSStyleSheet.insertRule()【疑似要素にも設定可能】
上の方法とは毛色が変わり、stylesheetにテキスト表現で与えられた新しいルールを挿入する方法。
疑似要素のstyleは直接いじれないっぽいので、この方法で設定する。
・ポイント:styleSheetにtitle属性を付けておく
<link rel="stylesheet" href="styles.css" title="main-style">
<div class="element"></div>
.element::before {
content: "sample";
}
・JSでstyleSheetを取得して、追加したいCSSをテキストで記述する。
// document内のstyleSheetsを配列で取得して、titleで絞り込み
const styleSheets = [...document.styleSheets];
const mainStyleSheet = styleSheets.filter(sheet => sheet.title === "main-style")[0];
// ルールを追加
mainStyleSheet.insertRule(".element::before {color: red; font-size: 2rem}");
// => sampleの文字が赤く大きくなります。
ちなみに余談ですが、document.styleSheets
の戻り値はStyleSheetList。MDNでは、
これは配列風のオブジェクトですが、 Array のメソッドを適用しての反復処理はできません。しかし標準の for ループと添字による反復処理、もしくは Array への変換ができます。
とあるので、スプレッド構文で配列として取得しています。
その他の参考
Discussion