JavaScriptからCSSのルールを追加する

忘却録。

コード

addLocalStyle.js// CSSを追加する
function addLocalStyle(text) {
  var style = document.createElement('style');
  style.type = 'text/css';
  style.textContent = text;
  document.head.appendChild(style);
}

※CSSの優先順位は、より後にあるものが優先される。
 そのため、<style>は、<head>内よりも<body>内にあるものの方が優先される。
 ただし、基本的に<style>は、<head>内に配置する要素である。

使用例

addLocalStyle('.sample1 { background: red !important; } .sample2 { background: blue !important; }');

サンプル

sample.html<style>
.sample-box {
  text-align: center;
}
.sample1,
.sample2 {
  width: 100px;
  height: 100px;
  margin: 0 auto 1em;
  border: 1px solid black;
  color: white;
  background: gray;
}
</style>
<script>
function addLocalStyle(text) {
  var style = document.createElement('style');
  style.type = 'text/css';
  style.textContent = text;
  document.head.appendChild(style);
}
function onClickSample() {
  addLocalStyle('.sample1 { background: red !important; } .sample2 { background: blue !important; }');
}
</script>
<div class='sample-box'>
  <div class='sample1'>sample1</div>
  <div class='sample2'>sample2</div>
  <button onclick='onClickSample();'>CSS追加</button>
</div>

sample1
sample2