6

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
1
  • 2
    Apart from the issue with IE not liking to set innerHTML on various elements like <head>: don't ever use innerHTML+=. 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. Commented Apr 20, 2010 at 15:30

2 Answers 2

14

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);
brasofilo
26.2k15 gold badges96 silver badges189 bronze badges
answered Apr 20, 2010 at 15:25
Sign up to request clarification or add additional context in comments.

2 Comments

Hi! This code works in Chrome. But in IE I got this error: Unexpected call to method or property access.
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
1

you can try:

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

answered Sep 23, 2021 at 22:53

1 Comment

Please add more detail

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.