How to add anything in <head> through jquery/javascript?
Solution 1
You can select it and add to it as normal:
$('head').append('<link />');
Solution 2
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
const link = document.createElement('link');
link.href = 'href';
link.rel = 'rel';
document.getElementsByTagName('head')[0].appendChild(link);
Solution 3
jQuery
$('head').append( ... );
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Solution 4
You can use innerHTML
to just concat the extra field string;
document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'
However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.
I haven't looked at the API in years, but you could also use document.write
, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.
Solution 5
Create a temporary element (e. g. DIV
), assign your HTML code to its innerHTML
property, and then append its child nodes to the HEAD
element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD
contents via its innerHTML
, this wouldn’t affect existing child elements of the HEAD
element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval()
.
Jitendra Vyas
Hi, I am Jitendra a front-end developer from India specializing in web standards, accessibility, and usability based development.
Updated on January 21, 2022Comments
-
Jitendra Vyas over 2 years
I'm working with a CMS, which prevents editing HTML source for
<head>
element.For example I want to add the following above the
<title>
tag:<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
-
Jitendra Vyas over 14 yearshow can i control order , where this link will be placed
-
nickf over 14 years
-
fredrik over 14 yearsdosen't appendChild require a DOM-element? ie. var elem = document.createElement() document.getElementsByTagName('head')[0].appendChild( elem );
-
David Hedlund over 14 yearswell yes. i just left that part as
...
because i didn't feel that was a central part of the question, and also, at the time of writing, there was no hands-on example as to what he wanted to put in head. but yes, it does need to be a DOM-element. -
serpent403 about 12 yearsI have put this in document.ready, but it doesn't append to my head contents
-
Pankaj Tiwari almost 12 yearsIt is adding link, but link not showing in page's view Source... I can view it from browser development tools like Firebug. Can I view link in view source also?
-
Bernhard Hofmann over 11 years@PankajTiwari You won't see it in the source view because the code appends it to the current document, not the original source (which was provided by the server). That's why FireBug and Chrome Dev tools are so useful.
-
Quentin over 10 yearsThat will delete the existing content and generate new elements. This can have undesirable side effects such as losing dynamically set DOM properties and causing scripts to be re-executed.
-
Dave over 10 yearsfor this reason you should use before $('head').html() to recover all the DOM properties
-
Quentin over 10 yearsUsing
.html()
won't recover all the DOM properties. (The most common instance of this problem, and the most visible, is when using similar code to add new fields to a form. The value attribute represents the default value of a field, so gettinghtml()
and then setting it back will reset all the existing fields to their default values). -
Dave over 10 yearsI can sure you I tested it in my code and it is working and all the DOM properties Works. Please, test yourself, I am working IE11
-
Eldho over 10 yearsi couddn't find the attached html using firebug or chrome dev tools. how to know whether its appended or not.
-
Pingwin Tux about 10 years@PankajTiwari Newer Firefox versions have build in dev tools. Just hit [ctrl+shift+k] (if you didn't change shortcuts) and choose inspector. If javascript change html source, it will be highlighted for some moment.
-
Klaider over 8 yearsThings that may be removed are events also.
-
mb897038 about 8 yearsThat is how I do it in the
body
, but can that really be done inside thehead
-tag? I was under the impression that the only allowed tags wherebase
,link
,meta
,title
,style
andscript
? -
Marat Tanalin about 8 yearsAFAICT, you have exactly those elements in your Ajax response. Don't you?
-
mb897038 about 8 yearsIndeed, but I still can't make it work with a div inside the head tag. It seems like Chrome is "smart" enough to display the content of the div in the body anyway.
-
Marat Tanalin about 8 yearsYou've probably not read the answer carefully. ;-) The
DIV
element is just a temporary container for the purpose of parsing HTML code. You shouldn't insert theDIV
itself to theHEAD
. You should insert its child nodes. Please see the example I've added to the answer. -
Ray Foss over 7 yearsWorks with script elements!
-
Gaetan L. about 4 yearsWhat does while (temp.firstChild) ? (sorry about the necropost)
-
Marat Tanalin about 4 years@GaetanL. “While there are child elements inside the
temp
element.” See Node.firstChild() docs. -
Crhistian Ramirez over 3 yearsHow would I append an html string? I am provided this html dynamically and don't know the structure of it ahead of time to convert it to an html element
-
nickf over 3 yearsIf you're sure the content is safe (ie: not from user input), maybe it'd work to put the content into a temporary element and then move elements into the head: ``` const tmp = document.createElement('div'); tmp.innerHTML = theStringOfDefinitelySafeHTML; for (const el of [...tmp.children]) document.head.appendChild(el); ```
-
Harendra Chauhan about 3 yearsYou can also use
document.head.innerHTML += '<link rel="stylesheet>...'
Just Short of your Code