How to create a 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?

18 Answers
18

Leave a Comment