I need to inject style elements into the head section of my html using JavaScript. For some context I am using webpack to inject styles. I have a function that is supposed to inject styles at an id inside of my head tags.
This is what my html looks like:
function insertAtElement(element) {
var target = document.getElementById(
"inject-theme-styles-here"
);
target.appendChild(element);
}
<head>
<meta charset="UTF-8" />
<title>Webpack tutorial</title>
<noscript id="inject-theme-styles-here"></noscript>
</head>
<body>
<div id="root"></div>
</body>
I am not getting my desired output. In the element tab in chrome it adds it inside the tag. But I need it to be added right below it not inside of it.
If you want your element to be added after target, instead of using target.appendChild(element); which appends a child element to target, use the following:
target.parentNode.insertBefore(element, target.nextSibling);
Create manually a script, set the src attribute and put it inside the head using tag name (or querySelector if you wish)
// create a script element
let theScript = document.createElement("script");
// define it as javascript script
theScript.setAttribute("type","text/javascript");
// set the src
theScript.setAttribute("src","src/myscript.js");
// insert into the head
document.getElementsByTagName("head")[0].appendChild(theScript);