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?
asked Apr 20, 2010 at 15:21
Aleksandr Ivanov
2,7965 gold badges27 silver badges35 bronze badges
2 Answers 2
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);
Sign up to request clarification or add additional context in comments.
2 Comments
Aleksandr Ivanov
Hi! This code works in Chrome. But in IE I got this error: Unexpected call to method or property access.
Aleksandr Ivanov
I found the solution. Problem was in this line: s.appendChild(document.createTextNode("a{font-size:100px;}"); See how to fix it here: phpied.com/dynamic-script-and-style-elements-in-ie
you can try:
let header = document.querySelector('head')
let newElement = document.createElement('p')
newElement.style.color = "lime"
newElement.style.fontSize = ".5rem"
header.append(newElement)
1 Comment
Muhammedogz
Please add more detail
default
innerHTMLon 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.