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
Is nicer
Works with Chrome?
Or maybe
This is a non-standard thing I should avoid
Three working browsers are great and who uses Chrome anyway?
Try adding the
style
element to thehead
rather than thebody
.This was tested in IE (7-9), Firefox, Opera and Chrome:
200% working code,example above
If the problem you're facing is 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.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.This will work in IE 5.5 upwards
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+).
Demo: codepen, jsfiddle
An example that works and are compliant with all browsers :
Here's a script which adds IE-style
createStyleSheet()
andaddRule()
methods to browsers which don't have them:You can add external files via
and dynamically create rules via