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?
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?
Share Improve this question asked Apr 20, 2010 at 15:21 Aleksandr IvanovAleksandr Ivanov 2,7865 gold badges27 silver badges35 bronze badges 1 |2 Answers
Reset to default 14Create 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);
you can try:
let header = document.querySelector('head')
let newElement = document.createElement('p')
newElement.style.color = "lime"
newElement.style.fontSize = ".5rem"
header.append(newElement)
innerHTML
on various elements like<head>
: don't ever useinnerHTML+=
. You'd be serialising all the nodes inside the head element to HTML, adding a string and then parsing them back, losing all non-serialisable content in the process. This is always to be avoided. – bobince Commented Apr 20, 2010 at 15:30