0

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Chris
  • 437
  • 1
  • 4
  • 18
  • 1
    Why are you using a `noscript` tag? Because that's [not for what you seem to think](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript). – Mike 'Pomax' Kamermans Sep 13 '21 at 20:13
  • Im not sure I didnt want to use a div in the head section what are the other options? – Chris Sep 13 '21 at 20:15
  • you insert `` or ` – Mike 'Pomax' Kamermans Sep 13 '21 at 20:16

2 Answers2

1

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);
George Sun
  • 968
  • 8
  • 21
0

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);    
Coffezilla
  • 376
  • 2
  • 7