Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add CSS with Javascript?

Tags:

javascript

css

People also ask

Can you style JavaScript with CSS?

Ignoring inline styles, the other approach that we can use to introduce elements to the goodness that is CSS styling involves JavaScript. We can use JavaScript to directly set a style on an element, and we can also use JavaScript to add or remove class values on elements which will alter which style rules get applied.

Where do I put CSS JavaScript?

You should put CSS in the <head> because that's what the specification says do to. If you have more than one CSS file, they will be loaded in the order you put them in the code. If there is style in the second CSS file, it overwrites the style in the first; That will happen by design.

How do I link CSS and JavaScript in HTML?

To link a CSS file with your HTML file, you have to write the next script on your HTML file inside the head tag. To link a Js file with your HTML, you only have to add the source of the script inside the body tag or outside; it doesn't matter.


The simple-and-direct approach is to create and add a new style node to the document.

// Your CSS as text
var styles = `
    .qwebirc-qui .ircwindow div { 
        font-family: Georgia,Cambria,"Times New Roman",Times,serif;
        margin: 26px auto 0 auto;
        max-width: 650px;
    }
    .qwebirc-qui .lines {
        font-size: 18px;
        line-height: 1.58;
        letter-spacing: -.004em;
    }

    .qwebirc-qui .nicklist a {
        margin: 6px;
    }
`

var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)

You can also do this using DOM Level 2 CSS interfaces (MDN):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:

sheet.addRule('strong', 'color: red;', -1);

There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.

You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.


The solution by Ben Blank wouldn't work in IE8 for me.

However this did work in IE8

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML as well instead of a creating a new text node:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

Shortest One Liner

// One liner function:
const addCSS = s => document.head.appendChild(document.createElement("style")).innerHTML=s;

// Usage: 
addCSS("body{ background:red; }")

You can add classes or style attributes on an element by element basis.

For example:

<a name="myelement" onclick="this.style.color='#FF0';">text</a>

Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala

this.className='classname';

If you want to do this in a javascript function, you can use getElementByID rather than 'this'.