Update and rename newCSSRule.md to injectCSS.md

This commit is contained in:
Angelos Chalaris
2020-10-15 22:18:00 +03:00
committed by GitHub
parent b325b05dc3
commit 1072a8f394
2 changed files with 24 additions and 23 deletions

24
snippets/injectCSS.md Normal file
View File

@ -0,0 +1,24 @@
---
title: injectCSS
tags: browser,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, `document.head` and `Element.appendChild()` to append the new element to the document head.
- Return the newly created `style` element.
```js
const injectCSS = css => {
let el = document.createElement('style');
el.type = 'text/css';
el.innerText = css;
document.head.appendChild(el);
return el;
}
```
```js
injectCSS('body { background-color: #000 }'); // '<style type="text/css">body { background-color: #000 }</style>'
```