Inject CSS

JavaScript, Browser, CSS · Oct 22, 2020

Injects the given CSS code into the current document

  • Use Document.createElement() to create a new style element and set its type to text/css.
  • Use Element.innerText to set the value to the given CSS string.
  • Use Document.head and Element.appendChild() to append the new element to the document head.
  • Return the newly created style element.
const injectCSS = css => {
  let el = document.createElement('style');
  el.type = 'text/css';
  el.innerText = css;
  document.head.appendChild(el);
  return el;
};
injectCSS('body { background-color: #000 }');
// '<style type="text/css">body { background-color: #000 }</style>'

More like this

  • Prefix CSS property

    Prefixes a CSS property based on the current browser.

    JavaScript, Browser · Oct 22, 2020

  • Get element ancestors

    Returns all the ancestors of an element from the document root to the given element.

    JavaScript, Browser · Jan 5, 2021

  • Check if HTML element has class

    Checks if the given element has the specified class.

    JavaScript, Browser · Oct 19, 2020