WilliamK
WilliamK

Reputation: 781

Insert html between the head tags using JavaScript

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;

Upvotes: 5

Views: 8836

Answers (2)

inhan
inhan

Reputation: 7470

Here's how you can do that using the DOM methods.

var scrp = document.createElement('script');
scrp.type = 'text/javascript';
// approach 1:
scrp.innerHTML = "alert('OK');";
// approach 2:
var txt = document.createTextNode("console.log('hi');");
scrp.appendChild(txt);
document.head.appendChild(scrp);

Upvotes: 0

Jordan
Jordan

Reputation: 32522

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.

Upvotes: 11

Related Questions