<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
title
>
How to add content in head section
using jQuery/JavaScript?
</
title
>
</
script
>
</
head
>
<
body
>
<
h1
style
=
"color: green;"
>
GeeksforGeeks
</
h1
>
<
b
>
How to add content in head section using jQuery/JavaScript?
</
b
>
<
button
onclick
=
"addStylesheet()"
>
Add Stylesheet to head
</
button
>
<
br
>
<
button
onclick
=
"addJS()"
>
Add JavaScript to head
</
button
>
<
br
>
<
b
>Current Head Element</
b
>
<
br
>
<
textarea
cols
=
"80"
rows
=
"14"
class
=
"head-element"
>
</
textarea
>
<
script
>
function addStylesheet() {
let linkToAdd =
document.createElement('link');
// Link to water.css stylesheet
linkToAdd.href =
linkToAdd.rel = 'stylesheet';
// Select the head element
// and append the created link
$('head').append(linkToAdd);
// Update textarea
updateHeadOutput();
}
function addJS() {
let scriptToAdd =
document.createElement('script');
scriptToAdd.type = 'text/javascript';
// Create contents of the script
let inlineScript = document.createTextNode(
"console.log('Script Loaded Successfully');");
scriptToAdd.appendChild(inlineScript);
// Uncomment to load script from another
// file
// scriptToAdd.src = 'myscript.js';
// Select the head element
// and append the script
$('head').append(scriptToAdd);
// Update textarea
updateHeadOutput();
}
function updateHeadOutput() {
document.querySelector(".head-element")
.textContent = document.head.innerHTML;
}
updateHeadOutput();
</
script
>
</
body
>
</
html
>