これを行う方法はいくつかありますが、最も簡単な方法は、<style>
要素を作成し、そのtextContentプロパティを設定して、ページの に追加することです<head>
。
/**
* Utility function to add CSS in multiple passes.
* @param {string} styleString
*/
function addStyle(styleString) {
const style = document.createElement('style');
style.textContent = styleString;
document.head.append(style);
}
addStyle(`
body {
color: red;
}
`);
addStyle(`
body {
background: silver;
}
`);
必要に応じて、これを少し変更して、CSS がaddStyle()
追加されるのではなく呼び出されたときに置き換えられるようにすることができます。
/**
* Utility function to add replaceable CSS.
* @param {string} styleString
*/
const addStyle = (() => {
const style = document.createElement('style');
document.head.append(style);
return (styleString) => style.textContent = styleString;
})();
addStyle(`
body {
color: red;
}
`);
addStyle(`
body {
background: silver;
}
`);
IE 編集: IE9 以下では最大 32 個のスタイルシートしか許可されないことに注意してください。そのため、最初のスニペットを使用するときは注意してください。この数は IE10 で 4095 に増えました。
2020編集:この質問は非常に古いですが、それでも時々通知が届くので、コードを更新して少し現代的にし、に置き換え.innerHTML
ました.textContent
. innerHTML
この特定のインスタンスは安全ですが、XSS 攻撃ベクトルになる可能性があるため、可能な限り回避することをお勧めします。