Inject CSS Stylesheet as String Using JavaScript

Inject CSS stylesheet as string using Javascript

There are a couple of ways this could be done, but the simplest approach is to create a <style> element, set its textContent property, and append to the page’s <head>.

/**
* Utility function to add CSS in multiple passes.
* @param {string} styleString
*/
function addStyle(styleString) {
const style = document.createElement('style');
style.textContent = styleString;
document.head.append(style);
}

addStyle(`
body {
color: red;
}
`);

addStyle(`
body {
background: silver;
}
`);

If you want, you could change this slightly so the CSS is replaced when addStyle() is called instead of appending it.

/**
* Utility function to add replaceable CSS.
* @param {string} styleString
*/
const addStyle = (() => {
const style = document.createElement('style');
document.head.append(style);
return (styleString) => style.textContent = styleString;
})();

addStyle(`
body {
color: red;
}
`);

addStyle(`
body {
background: silver;
}
`);

IE edit: Be aware that IE9 and below only allows up to 32 stylesheets, so watch out when using the first snippet. The number was increased to 4095 in IE10.

2020 edit: This question is very old but I still get occasional notifications about it so I’ve updated the code to be slightly more modern and replaced .innerHTML with .textContent. This particular instance is safe, but avoiding innerHTML where possible is a good practice since it can be an XSS attack vector.

Injecting CSS like HTML through JavaScript into the DOM

You can inject CSS through vanilla JavaScript:

  • Create a style element
  • Set its content to your string with the CSS
  • Add the style element to the head of the DOM

Example 1 (for older browser too):

// get the head and create a style elementvar head = document.head || document.getElementsByTagName('head')[0];var style = document.createElement('style');
style.type = 'text/css';
// create your CSS as a stringvar css = '.my-element { color: white; background: cornflowerblue; }';
// IE8 and below.if (style.styleSheet) { style.styleSheet.cssText = css;} else { style.appendChild(document.createTextNode(css));}
// add it to the headhead.appendChild(style);
<div class="my-element">Text</div>

Injecting a CSS stylesheet using Javascript

If the stylesheet is a separate resource, (You've confirmed in a comment that it is), you link it with link rel="stylesheet":

var link = document.createElement("link");
link.rel = "stylesheet";
link.href = "mystyle.css";
document.head.appendChild(link);
// Or document.querySelector("head").appendChild(link);
// But I don't think that's necessary on any vaguely-modern browser

(Can't really do a live example of this one with Stack Snippets.)


If you have it as a string, you apply it with a style element:

var style = document.createElement("style");
style.appendChild(document.createTextNode("/*...style text here...*/"));
document.head.appendChild(style);

Live example:

var style = document.createElement("style");style.appendChild(document.createTextNode(  "#p1 { background-color: yellow}"));document.head.appendChild(style);
<p id="p1">Altering style of first paragraph via Javascript.</p><p id="p2">Altering style of second paragraph via Javascript.</p>

Add stylesheet to Head using javascript in body

Update: According to specs, the link element is not allowed in the body. However, most browsers will still render it just fine. So, to answer the questions in the comments - one really has to add link to the head of the page and not the body.

function addCss(fileName) {

var head = document.head;
var link = document.createElement("link");

link.type = "text/css";
link.rel = "stylesheet";
link.href = fileName;

head.appendChild(link);
}

addCss('{my-url}');

Or a little bit easier with jquery

function addCss(fileName) {
var link = $("<link />",{
rel: "stylesheet",
type: "text/css",
href: fileName
})
$('head').append(link);
}

addCss("{my-url}");

Original answer:

You don't need necessarily add it to the head, just add it to the end of body tag.

$('body').append('<link rel="stylesheet" type="text/css" href="{url}">')

as Juan Mendes mentioned, you can insert stylesheet to the head instead

$('head').append('<link rel="stylesheet" type="text/css" href="{url}">')

And the same without jQuery (see code above)

Inject css inline into elements using js

You could create a template class in your css file like this

.colorOnHover a:hover {
color: red;
}

And then you can use document.querySelector to get the element and add the colorOnHover to the classList of that element.

// your js file
const element = document.querySelector(''); // pass in the ID or the class of the element you want to add the changes to
(function() {
element.classList.add('colorOnHover');
})();
// this will add `colorOnHover` class to the classList and apply the css defined to the class in your css file.

Make sure to link the javascript & css file (if any) using <script src = "pathHere" defer></script> and <link rel = 'stylesheet' href = "pathHere>" respectively

update : since the op didn't want to use querySelector

You could use document.createElement('style') and append it to the html file, it would be similar to manually inserting a tag

(function() {
const styleEl = document.createElement('style');
styleEl.textContent = '.one .two a:hover{color:red;}';
document.head.append(styleEl);
console.log('added new style tag');
})();

How to load up CSS files using Javascript?

Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use setAttribute unfortunately IE6 doesn't support it consistently.

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.example/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}

This example checks if the CSS was already added so it adds it only once.

Put that code into a JavaScript file, have the end-user simply include the JavaScript, and make sure the CSS path is absolute so it is loaded from your servers.

VanillaJS

Here is an example that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:

<script type="text/javascript">
var file = location.pathname.split( "/" ).pop();

var link = document.createElement( "link" );
link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";

document.getElementsByTagName( "head" )[0].appendChild( link );
</script>

Insert the code just before the closing head tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (.js) file will cause a Flash of unstyled content (FOUC) to appear.

Injecting CSS String as New Document Stylesheet

You could use document.stylesheets for this purpose. It gives you access to the style sheets within a page.

Check this article: http://kentbrewster.com/creating-dynamic-stylesheets/ — It's a bit older and not jQuery–centric, but I'm sure you can adjust it to your needs. I've used this technique a few years back and I believe it worked fine in all browsers after tweaking a bit.

Here's a bit more information on the stylesheets property:

  • http://www.quirksmode.org/dom/changess.html
  • https://developer.mozilla.org/en/DOM/document.styleSheets

Create a CSSStyleSheet object from a CSS string?

Here's a function that does this:

function CSSString2CSSStyleSheet ( css ) {
const style = document.createElement ( 'style' );
style.innerText = css;
document.head.appendChild ( style );
const {sheet} = style;
document.head.removeChild ( style );
return sheet;
}

How do you add CSS with Javascript?

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.

Add CSS to <head> with JavaScript?

As you are trying to add a string of CSS to <head> with JavaScript?
injecting a string of CSS into a page it is easier to do this with the <link> element than the <style> element.

The following adds p { color: green; } rule to the page.

<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />

You can create this in JavaScript simply by URL encoding your string of CSS and adding it the HREF attribute. Much simpler than all the quirks of <style> elements or directly accessing stylesheets.

var linkElement = this.document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('href', 'data:text/css;charset=UTF-8,' + encodeURIComponent(myStringOfstyles));

This will work in IE 5.5 upwards

The solution you have marked will work but this solution requires fewer dom operations and only a single element.



Related Topics



Leave a reply



Submit