Insert html between the head tags using JavaScript

javascript

Solution

Assuming you always actually have a `<head>`, you can do this:

document.getElementsByTagName("head")[0].innerHTML += "<whatever />";

You can of course also use the DOM model instead of innerHTML.

Problem

In previous quests we looked at how we could insert code into a tag and with multiple attributes, and before the first tag (doctype), but what about inserting code between the head tags such as new CSS style sheets and JavaScript inserts. I did searched here and found some related posts, but no examples that work. For example, how to add the following lines of code using JavaScript only... ``` <link rel="stylesheet" type="text/css" href="chrome.css" /> <script type="text/javascript" src="chrome.js"></script> ``` One suggestion below looked promising, but when tested it didn't actually work, for example... ``` var refScript = "<SCRIPT>alert('OK');</SCRIPT>"; document.getElementsByTagName("head")[0].innerHTML += refScript; ```

Original source