Add stylesheet to Head using javascript in body

Viewed 95954

I'm working with a CMS that prevents us from editing the head section. I need to add css stylesheet to the site, right after the tag. Is there a way to do this with JS, where I can add a script to the bottom of the page (I have access to add script right before the tag) that would then inject the stylesheet into the head section?

5 Answers

You can use pure javascript and still elegance in the modern browser.

const range = document.createRange()
const frag = range.createContextualFragment(`THE CONTENT IS THE SAME AS THE HTML.`)
document.querySelector("YOUR-NODE").append(frag) 

It's very easy to add any HTML code.

Document

Example 1

Add the style on the head by javascript.

<head></head><body><button class="hover-danger">Hello World</button></body>
<script>
  const range = document.createRange()
  const frag = range.createContextualFragment(`
<style>
  .hover-danger:hover{
    background-color: red;
    font-weight: 900
  }
</style>
`
)
  document.querySelector("head").append(frag)  
</script>

Example 2

Import CSS, JS, and modify the existing stylesheet.

<head></head>
<body><button class="btn btn-primary hover-danger">Hello world</button></body>

<script>
  const range = document.createRange()
  const frag = range.createContextualFragment(`
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"/>
`)
  document.querySelector("head").append(frag)

  window.onload = () => {
    //  If you don't want to import the new source, you can consider adding the data to exists source.
    const nodeLink = document.querySelector(`link[href^="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"]`) // ^: match begin with my input
    if (nodeLink)  { // !== null
      const stylesheet = nodeLink.sheet
      const myCSS = `
background-color:red;
font-weight: 900;
`
      stylesheet.insertRule(`.hover-danger:hover{ ${myCSS} }`, stylesheet.cssRules.length)
    }
  }
</script>

You must have permission to modify the CSS directly

If you get the error:

Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules,

then you can reference: https://stackoverflow.com/a/49994161/9935654

Here is a simple one-liner to add a stylesheet:

document.head.insertAdjacentHTML('beforeend', `<link typs="text/css" rel="stylesheet" href="<Source URL>">`);
Related