Files
30-seconds-of-code/snippets/injectCSS.md
Isabelle Viktoria Maciohsek caa67e2a49 Update snippet descriptions
2020-10-20 23:02:01 +03:00

720 B

title, tags
title tags
injectCSS browser,css,intermediate

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>'