Dynamically add css to page via javascript

Solution 1:

If you want to add CSS as text

var style = document.createElement('style');
style.innerHTML = 'content';
document.head.appendChild(style);

If you want to add a CSS file

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', 'css/my.css');
document.head.appendChild(link);

Solution 2:

I have traditionally appended a <style> block when doing elements.

var style_rules = [];

style_rules.push("#" + myElemId + " { /* Rules */ } ");
/* ... */

var style = '<style type="text/css">' + style_rules.join("\n") + "</style>";
$("head").append(style);

An important thing to note is that because you don't know what any of the existing styles is, or what id's might conflict on the page, it's very useful to keep track of your id's inside your JavaScript application, then using those to populate the injected <style> block. I also tend to run my names through a prefix function to ensure that the generic names of wrapper, and unit do not conflict (they are turned into something like myunique_wrapper and myunique_unit.

Incorporating a basic CSS reset like #myWrapper {margin: 0; padding: 0} can be a decent starting platform for building your own custom styles.

Addressing your unique case, a live preview so to speak, I would designate a div with standard elements. Then when they click "update" read in the rules and append them to the head. If you want to negate any residual effects from past rules you can remove the last <style> element or better yet give your <style> element an id. I'm not sure if that kind of selection would work, but it should.

Solution 3:

var element = document.createElement('style');
element.setAttribute('type', 'text/css');

if ('textContent' in element) {
  element.textContent = css;
} else {
  element.styleSheet.cssText = css;
}

document.getElementsByTagName('head')[0].appendChild(element);