Mocktheduck
Mocktheduck

Reputation: 1423

Injecting CSS like HTML through JavaScript into the DOM

I'm wondering if I can add CSS code as a string the way I can add HTML code through JavaScript, e.g.:

var div = document.createElement("div");
div.innerHTML =
  '<div id="hs1"></div>\n' +
  '<div id="hs2"></div>\n' +
  '<div id="hs3"></div>\n'

document.body.appendChild(div);

Can I, in a similar fashion, add a giant CSS code?

Basically I have HTML + CSS + JS code, that I want to put into a .js file instead of a .html. I'm new to web development, so I don't know. Is this even possible?

Upvotes: 2

Views: 5443

Answers (4)

user7637745
user7637745

Reputation: 985

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 element
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');

style.type = 'text/css';

// create your CSS as a string
var 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 head
head.appendChild(style);
<div class="my-element">Text</div>

Example 2 (for newer browsers):

// create a style element
var style = document.createElement('style');

// add the CSS as a string
style.innerHTML = '.my-element { color: white; background: cornflowerblue; }';

// add it to the head
document.getElementsByTagName('head')[0].appendChild(style);
<div class="my-element">Text</div>

Example 3 (ES6):

// create a style element
const style = document.createElement('style');

// add the CSS as a string using template literals
style.appendChild(document.createTextNode(`
  .my-element { 
    color: white; 
    background: cornflowerblue; 
  }`
));

// add it to the head
const head = document.getElementsByTagName('head')[0];
head.appendChild(style);
<div class="my-element">Text</div>

Upvotes: 10

Salman Arshad
Salman Arshad

Reputation: 272386

You can use CSSStyleSheet interface to manipulate a stylesheet. The following example shows you how to manipulate an existing stylesheet. This method allows you to specify the position of the inserted rule instead of always appending it at the end:

document.querySelector("#button-1").addEventListener("click", function() {
  var sheet = document.querySelector("style").sheet;
  var color = "rgb(" + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ")";
  sheet.insertRule("p { background-color: " + color + "; }", sheet.cssRules.length);
});
/* this stylesheet intentionally left blank */
<button id="button-1">Modify Stylesheet</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum urna risus, non finibus sem fermentum eget. In at libero a justo molestie semper. Praesent sit amet massa justo. Donec aliquet lobortis justo tincidunt ultrices.</p>

Upvotes: 1

SirPilan
SirPilan

Reputation: 4857

Have you acutally tried?

document.getElementById('myButton').onclick = function() {
  var sc = document.createElement('style');
  sc.innerHTML = "#myDiv { padding: 10px; border: 1px dashed blue; }";
  
  document.getElementById('myDiv').appendChild( sc );
}
<div id="myDiv">
  Test 123
</div>
<button id="myButton">Click Me!</button>

If you have a GIANT css file. Its better so load the file itself. You can create a style tag like above and set the href attribute to load it.

Upvotes: 1

zero298
zero298

Reputation: 26920

Yes, have you tried creating a <style> tag, populating it with rules, and injecting it?

const style = document.createElement("style");
style.innerHTML = "#foo{background-color: green;}";
document.head.appendChild(style);
<div id="foo">Foo bar</div>

Upvotes: 3

Related Questions