Aleksandr Ivanov
Aleksandr Ivanov

Reputation: 2786

Append some HTML into the HEAD tag?

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?

Upvotes: 6

Views: 18511

Answers (2)

RoToRa
RoToRa

Reputation: 38400

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);

Upvotes: 14

YassBan
YassBan

Reputation: 91

you can try:

let header = document.querySelector('head')
let newElement = document.createElement('p')
newElement.style.color = "lime"
newElement.style.fontSize = ".5rem"
header.append(newElement)

Upvotes: 1

Related Questions