views:

57

answers:

1

Hi!

I want to add some style to head tag in html page using javascript.

var h = document.getElementsByTagName('head').item(0);
h.innerHTML += '<style>a{font-size:100px;}</style>';

But when I run this code in IE8 I see this error message: Could not set the innerHTML property. Invalid target element for this operation.

Any ideas?

+3  A: 

Create the style element with createElement:

var h = document.getElementsByTagName('head').item(0);
var s = document.createElement("style");
s.type = "text/css"; 
s.appendChild(document.createTextNode("a{font-size:100px;}");
h.appendChild(s);
RoToRa
Hi!This code works in Chrome. But in IE I got this error: Unexpected call to method or property access.
Alex
I found the solution. Problem was in this line: s.appendChild(document.createTextNode("a{font-size:100px;}");See how to fix it here: http://www.phpied.com/dynamic-script-and-style-elements-in-ie/
Alex