From 1072a8f3940d68a81bbb2ef65f8fcc98b575aeab Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Thu, 15 Oct 2020 22:18:00 +0300 Subject: [PATCH] Update and rename newCSSRule.md to injectCSS.md --- snippets/injectCSS.md | 24 ++++++++++++++++++++++++ snippets/newCSSRule.md | 23 ----------------------- 2 files changed, 24 insertions(+), 23 deletions(-) create mode 100644 snippets/injectCSS.md delete mode 100644 snippets/newCSSRule.md diff --git a/snippets/injectCSS.md b/snippets/injectCSS.md new file mode 100644 index 000000000..961b5b307 --- /dev/null +++ b/snippets/injectCSS.md @@ -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 }'); // '' +``` diff --git a/snippets/newCSSRule.md b/snippets/newCSSRule.md deleted file mode 100644 index 882f63bdb..000000000 --- a/snippets/newCSSRule.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: newCSSRule -tags: dom,html,begginer ---- - -Creates a new CSS rule. - -- Creates new style element. -- Appends the created style element to head. -- Defines the type of element and appends CSS rules to it. - -```js -const newCSSRule = rule => { - let css = document.createElement('style'); - document.getElementsByTagName('head')[0].appendChild(css); - css.type = 'text/css'; - css.appendChild(document.createTextNode(rule)); -} -``` - -```js -newCSSRule('body { background-color: #000 }'); // -```