You are on page 1of 7

html - How to create a <style> tag with Javascript - Stack Overflow 2017/09/12 17(05

x Dismiss

Join the Stack Overflow Community

Stack Overflow is a community of 7.7 million


programmers, just like you, helping each other.
Join them; it only takes a minute:

Sign up

How to create a <style> tag with Javascript

I'm looking for a way to insert a <style> tag into an HTML page with javascript.

The best way I found so far:

var divNode = document.createElement("div");


divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);

This works in Firefox, Opera and Internet Explorer but not in Google Chrome. Also it's a bit ugly with the <br>
in front for IE.

Does anyone know of a way to create a <style> tag that

1. is nicer
2. works with Chrome?

Or maybe

1. this is a non-standard thing I should avoid


2. three working browsers are great and who uses Chrome anyway?

I appreciate any advice on this.


javascript html css

edited Aug 28 at 18:11 asked Feb 7 '09 at 22:12


serv-inc Arend
5,579 2 31 54

9 Answers

file:///Users/ryota/Downloads/html%20-%20How%20to%20create%20tyle%3E%20tag%20with%20Javascript%20-%20Stack%20Overflow.html Page 1 of 7
html - How to create a <style> tag with Javascript - Stack Overflow 2017/09/12 17(05

Try adding the style element to the head rather than the body .

This was tested in IE (7-9), Firefox, Opera and Chrome:

var css = 'h1 { background: red; }',


head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}

head.appendChild(style);

edited Feb 9 '14 at 17:43 answered Feb 7 '09 at 22:25


TomFuertes Christoph
5,015 3 25 44 113k 25 135 200

FYI, document.head (https://developer.mozilla.org/en/DOM/document.head) is supported in


8
all major browsers. Rob W Feb 23 '12 at 18:12

@RobW - It's not supported in IE8 and below. It's supported in Modern browsers, but not all
22
major ones. Tim Mar 3 '12 at 5:24

why not just use document.querySelector("head") ? It's event supported by IE8 by


3
source (https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector) allenhwkim Oct 8 '14 at
14:06

@allenhwkim: the answer predates introduction of querySelector() ; today, I'd probably go


4
with document.head , available since IE9 Christoph Oct 8 '14 at 14:17

@Christoph why are there two style.styleSheet.cssText style.appendChild cases?


26
Which browser(s) are you working around? Don McCurdy Feb 2 '16 at 2:44

file:///Users/ryota/Downloads/html%20-%20How%20to%20create%20yle%3E%20tag%20with%20Javascript%20-%20Stack%20Overflow.html Page 2 of 7
html - How to create a <style> tag with Javascript - Stack Overflow 2017/09/12 17(05

I'm assuming that you're wanting to insert a style tag versus a link tag (referencing
an external CSS), so that's what the following example does:

<html>
<head>
<title>Example Page</title>
</head>
<body>
<span>
This is styled dynamically via JavaScript.
</span>
</body>
<script type="text/javascript">
var styleNode = document.createElement('style');
styleNode.type = "text/css";
// browser detection (based on prototype.js)
if(!!(window.attachEvent && !window.opera)) {
styleNode.styleSheet.cssText = 'span { color: rgb(255, 0, 0); }';
} else {
var styleText = document.createTextNode('span { color: rgb(255, 0, 0);
} ');
styleNode.appendChild(styleText);
}
document.getElementsByTagName('head')[0].appendChild(styleNode);
</script>
</html>

Also, I noticed in your question that you are using innerHTML . This is actually a non-
standard way of inserting data into a page. The best practice is to create a text node and
append it to another element node.

With respect to your final question, you're going to hear some people say that your work
should work across all of the browsers. It all depends on your audience. If no one in your
audience is using Chrome, then don't sweat it; however, if you're looking to reach the
biggest audience possible, then it's best to support all major A-grade browsers

edited Feb 8 '09 at 4:37 answered Feb 7 '09 at 22:22


Tom
7,846 4 41 58

This is basically the same as my solution; neither of them works in IE! Christoph Feb 7 '09 at
1
22:31

Appending a text node doesn't work in IE. But putting the style element in the head makes my
solution work in Chrome! :-) Arend Feb 7 '09 at 22:34

for IE, use styleNode.styleSheet.cssText = ... Christoph Feb 7 '09 at 22:37


1

Alright, cool. I updated the above code to include browser detection so that it will apply the
dynamic style addition properly. Tom Feb 8 '09 at 4:38

(Very late comment) "It all depends on your audience. If no one in your audience is using
5
Chrome, then don't sweat it" This attitude is what leads to people being locked into IE6 for years
after IE7 and even IE8 are available. "But the web application I have to use only works in IE6"
Stephen P May 8 '10 at 0:49

file:///Users/ryota/Downloads/html%20-%20How%20to%20create%20yle%3E%20tag%20with%20Javascript%20-%20Stack%20Overflow.html Page 3 of 7
html - How to create a <style> tag with Javascript - Stack Overflow 2017/09/12 17(05

Here's a script which adds IE-style createStyleSheet() and addRule() methods to


browsers which don't have them:

if(typeof document.createStyleSheet === 'undefined') {


document.createStyleSheet = (function() {
function createStyleSheet(href) {
if(typeof href !== 'undefined') {
var element = document.createElement('link');
element.type = 'text/css';
element.rel = 'stylesheet';
element.href = href;
}
else {
var element = document.createElement('style');
element.type = 'text/css';
}

document.getElementsByTagName('head')[0].appendChild(element);
var sheet = document.styleSheets[document.styleSheets.length - 1];

if(typeof sheet.addRule === 'undefined')


sheet.addRule = addRule;

if(typeof sheet.removeRule === 'undefined')


sheet.removeRule = sheet.deleteRule;

return sheet;
}

function addRule(selectorText, cssText, index) {


if(typeof index === 'undefined')
index = this.cssRules.length;

this.insertRule(selectorText + ' {' + cssText + '}', index);


}

return createStyleSheet;
})();
}

You can add external files via

document.createStyleSheet('foo.css');

and dynamically create rules via

var sheet = document.createStyleSheet();


sheet.addRule('h1', 'background: red;');

edited Feb 23 '09 at 12:20 answered Feb 7 '09 at 23:18


Christoph
113k 25 135 200

This was very helpful to me in trying to load an external CSS file in a strange CMS context. I did
run into some trouble with the addRule / removeRule part, so I just elimated those, and
everything works fine. Kirkman14 Sep 27 '11 at 19:15

file:///Users/ryota/Downloads/html%20-%20How%20to%20create%20yle%3E%20tag%20with%20Javascript%20-%20Stack%20Overflow.html Page 4 of 7
html - How to create a <style> tag with Javascript - Stack Overflow 2017/09/12 17(05

An example that works and are compliant with all browsers :

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(ss);

edited Feb 8 '09 at 11:17 answered Feb 7 '09 at 22:23


belaz
750 4 12 30

wrong element: style has no rel or href attribute - did you mean link ? Christoph
4
Feb 7 '09 at 22:30

Right, corrected ;D belaz Feb 8 '09 at 11:18


3

what does link element has to do with the question? the OP asked for style element. This
1
answer has nothing to do with the question vsync Jun 9 '15 at 6:56

@vsync style is for adding inline styles, link is correct for stylesheet sources and this has
the advantage of avoiding cross-browser issues. majick Apr 12 '16 at 4:16

For those already using jQuery, you can use this one-liner:

$('<style>'+ styles +'</style>').appendTo(document.head);

So that's it. You can also save a reference to this element to change it later.

edited Jun 9 '16 at 9:39 answered Feb 22 '15 at 19:16


vsync
34.1k 28 122 158

file:///Users/ryota/Downloads/html%20-%20How%20to%20create%20yle%3E%20tag%20with%20Javascript%20-%20Stack%20Overflow.html Page 5 of 7
html - How to create a <style> tag with Javascript - Stack Overflow 2017/09/12 17(05

Here is a variant for dynamically adding a class

function setClassStyle(class_name, css) {


var style_sheet = document.createElement('style');
if (style_sheet) {
style_sheet.setAttribute('type', 'text/css');
var cstr = '.' + class_name + ' {' + css + '}';
var rules = document.createTextNode(cstr);
if(style_sheet.styleSheet){// IE
style_sheet.styleSheet.cssText = rules.nodeValue;
} else {
style_sheet.appendChild(rules);
}
var head = document.getElementsByTagName('head')[0];
if (head) {
head.appendChild(style_sheet);
}
}
}

edited Apr 28 '15 at 20:05 answered Dec 18 '09 at 17:29


iandotkelly Michael
6,776 8 33 60 59 1 1

Oftentimes there's a need to override existing rules, so appending new styles to the
HEAD doesn't work in every case.

I came up with this simple function that summarizes all not valid "append to the BODY"
approaches and is just more convenient to use and debug (IE8+).

window.injectCSS = (function(doc){
// wrapper for all injected styles and temp el to create them
var wrap = doc.createElement('div');
var temp = doc.createElement('div');
// rules like "a {color: red}" etc.
return function (cssRules) {
// append wrapper to the body on the first call
if (!wrap.id) {
wrap.id = 'injected-css';
wrap.style.display = 'none';
doc.body.appendChild(wrap);
}
// <br> for IE: http://goo.gl/vLY4x7
temp.innerHTML = '<br><style>'+ cssRules +'</style>';
wrap.appendChild( temp.children[1] );
};
})(document);

Demo: codepen (http://codepen.io/anon/pen/vtHCs), jsfiddle


(http://jsfiddle.net/8h09zkht/)

edited Aug 29 '15 at 6:07 answered Oct 7 '14 at 7:12


Garlaro
79 2 7

Worked perfectly in the latest Firefox, Chrome, and in ie8 (or at least the way I typed it in). I really
don't know why this doesn't have more points. Harry Pehkonen Apr 2 '15 at 13:35

This has no more points, because it is not valid, neither good thing to inject <style> tag
outside <head> tag. Style tag should appear nowhere else but within <head> tag. That's
widely adopted html standard. There is style attribute for inline styling and style attribute can be
applied to any tag within <body> tag, including <body> tag it self. Spooky Apr 24 '15 at
21:20

file:///Users/ryota/Downloads/html%20-%20How%20to%20create%20yle%3E%20tag%20with%20Javascript%20-%20Stack%20Overflow.html Page 6 of 7
html - How to create a <style> tag with Javascript - Stack Overflow 2017/09/12 17(05

All good, but for styleNode.cssText to work in IE6 with node created by javascipt, you
need to append the node to the document before you set the cssText;

further info @ http://msdn.microsoft.com/en-us/library/ms533698%28VS.85%29.aspx


(http://msdn.microsoft.com/en-us/library/ms533698%28VS.85%29.aspx)

answered Feb 24 '10 at 23:47


Tony
31 1

This object variable will append style tag to the head tag with type attribute and one
simple transition rule inside that matches every single id/class/element. Feel free to
modify content property and inject as many rules as you need. Just make sure that css
rules inside content remain in one line (or 'escape' each new line, if You prefer so).

var script = {

type: 'text/css', style: document.createElement('style'),


content: "* { transition: all 220ms cubic-bezier(0.390, 0.575, 0.565, 1.000);
}",
append: function() {

this.style.type = this.type;
this.style.appendChild(document.createTextNode(this.content));
document.head.appendChild(this.style);

}}; script.append();

edited Feb 16 '15 at 11:43 answered Feb 16 '15 at 11:00


Spooky
847 7 15

file:///Users/ryota/Downloads/html%20-%20How%20to%20create%20yle%3E%20tag%20with%20Javascript%20-%20Stack%20Overflow.html Page 7 of 7

You might also like