5

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;
1
  • 2
    document.head.appendChild() Commented Dec 6, 2012 at 15:49

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Will ("head") be case sensitive?
@WilliamK Nope. You can write head, HEAD, Head etc.
0

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

Comments

Your Answer

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.