Sometimes you want to insert complete CSS rules into specific page with JavaScript. Here is how.

JavaScript class (use Babel or something to transpile ES6 code into ES5):

class CSSRule {
  constructor() {
    this.sheet = (function() {
      // Create the <style> tag
      let style = document.createElement('style');
      // Add a media
      style.setAttribute('media', 'screen');
      // WebKit
      style.appendChild(document.createTextNode(''));
      // Add the <style> element to the page
      document.head.appendChild(style);
      return style.sheet;
    })();
  }
  addCSSRule(selector, rules) {
    if ('insertRule' in this.sheet) {
      this.sheet.insertRule(`selector { ${rules} }`, this.sheet.cssRules.length);
    } else if ('addRule' in sheet) {
      this.sheet.addRule(selector, rules, this.sheet.cssRules.length);
    }
  }
}

$(document).ready(function() {
  let title = $('#post-title');
  const style = new CSSRule();
  if (title && $(title).data('color')) {
    style.addCSSRule('.post-header .title h1',
                     `color: ${$(title).data('color')}`);
  }
});

Basically, we read data attribute of an element and use that value as color of h1 element. Code above will insert following code in your page:

<style media="screen">
  .post-header .title h1 { color: #def; }
</style>

If you already have <style> tag on your page, this code will insert that CSS rule at the end of that tag.

Share on: