[javascript] How do you add CSS with Javascript?

How do you add CSS rules (eg strong { color: red }) by use of Javascript?

This question is related to javascript css

The answer is


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)

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);
}

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'.


use .css in Jquery like $('strong').css('background','red');

_x000D_
_x000D_
$('strong').css('background','red');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<strong> Example_x000D_
</strong> 
_x000D_
_x000D_
_x000D_


Here's my general-purpose function which parametrizes the CSS selector and rules, and optionally takes in a css filename (case-sensitive) if you wish to add to a particular sheet instead (otherwise, if you don't provide a CSS filename, it will create a new style element and append it to the existing head. It will make at most one new style element and re-use it on future function calls). Works with FF, Chrome, and IE9+ (maybe earlier too, untested).

function addCssRules(selector, rules, /*Optional*/ sheetName) {
    // We want the last sheet so that rules are not overridden.
    var styleSheet = document.styleSheets[document.styleSheets.length - 1];
    if (sheetName) {
        for (var i in document.styleSheets) {
            if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
                styleSheet = document.styleSheets[i];
                break;
            }
        }
    }
    if (typeof styleSheet === 'undefined' || styleSheet === null) {
        var styleElement = document.createElement("style");
        styleElement.type = "text/css";
        document.head.appendChild(styleElement);
        styleSheet = styleElement.sheet;
    }

    if (styleSheet) {
        if (styleSheet.insertRule)
            styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
        else if (styleSheet.addRule)
            styleSheet.addRule(selector, rules);
    }
}

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 );
}

if you know at least one <style> tag exist in page , use this function :

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

usage :

CSS("div{background:#00F}");

Shortest One Liner

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

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


This easy example of add <style> in head of html

var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul {    margin-top: 0 !important;    margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";

document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head

Source Dynamic style - manipulating CSS with JavaScript


This is my solution to add a css rule at the end of the last style sheet list:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

YUI just recently added a utility specifically for this. See stylesheet.js here.


Here's a sample template to help you get started

Requires 0 libraries and uses only javascript to inject both HTML and CSS.

The function was borrowed from the user @Husky above

Useful if you want to run a tampermonkey script and wanted to add a toggle overlay on a website (e.g. a note app for instance)

_x000D_
_x000D_
// INJECTING THE HTML_x000D_
document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>';_x000D_
_x000D_
// CSS INJECTION FUNCTION_x000D_
//https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript_x000D_
function insertCss( code ) {_x000D_
    var style = document.createElement('style');_x000D_
    style.type = 'text/css';_x000D_
    if (style.styleSheet) {_x000D_
        // IE_x000D_
        style.styleSheet.cssText = code;_x000D_
    } else {_x000D_
        // Other browsers_x000D_
        style.innerHTML = code;_x000D_
    }_x000D_
    document.getElementsByTagName("head")[0].appendChild( style );_x000D_
}_x000D_
_x000D_
// INJECT THE CSS INTO FUNCTION_x000D_
// Write the css as you normally would... but treat it as strings and concatenate for multilines_x000D_
insertCss(_x000D_
  "#injection {color :red; font-size: 30px;}" +_x000D_
  "body {background-color: lightblue;}"_x000D_
)
_x000D_
_x000D_
_x000D_


Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:

function appendCSSToElement(element, CssProperties)
        {
            var existingCSS = $(element).attr("style");

             if(existingCSS == undefined) existingCSS = "";

            $.each(CssProperties, function(key,value)
            {
                existingCSS += " " + key + ": " + value + ";";
            });

            $(element).attr("style", existingCSS);

            return $(element);
        }

And then execute it with the new CSS attributes as an object.

appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });

This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.