2

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?

8
  • Just make your .css and .js files external and import them into the HTML view. Commented Jun 26, 2018 at 19:59
  • html+css to put in JS ? Commented Jun 26, 2018 at 19:59
  • 1
    Yes, have you tried creating a <style> tag, populating it with rules, and injecting it? Commented Jun 26, 2018 at 19:59
  • @RyanWilson I want to have only the .js file, without the .css. I want the .css code to go inside the .js somehow. Commented Jun 26, 2018 at 20:01
  • 1
    @Mocktheduck Ok. Seems like overkill to me. Commented Jun 26, 2018 at 20:05

4 Answers 4

10

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>

Sign up to request clarification or add additional context in comments.

Comments

3

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>

Comments

1

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.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.