{"id":4798,"date":"2022-03-28T02:00:00","date_gmt":"2022-03-28T00:00:00","guid":{"rendered":"https:\/\/alvarotrigo.com\/epa\/change-css-javascript\/"},"modified":"2025-06-11T11:36:05","modified_gmt":"2025-06-11T09:36:05","slug":"change-css-javascript","status":"publish","type":"post","link":"https:\/\/alvarotrigo.com\/blog\/change-css-javascript\/","title":{"rendered":"How To Change CSS With JavaScript [With Examples]"},"content":{"rendered":"\n<p>JavaScript is all about dynamic stuff and dealing with dynamic CSS changes is just one of the scenarios where JavaScript is exactly what we need.<\/p>\n\n\n\n<p>With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" data-src=\"https:\/\/alvarotrigo.com\/blog\/assets\/imgs\/2022-03-28\/modify-css-with-javascript.jpeg\" alt=\"How To Modify CSS With JavaScript - Best Ways\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" class=\"lazyload\" \/><\/figure>\n\n\n\n<p>Let&#8217;s get into the different ways we can do achieve this:<\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"1.-change-css-inline-properties-with-javascript\">1. Change CSS inline properties with JavaScript<\/h2>\n\n\n<p>Setting individual styles directly from JavaScript is one of the most common scenarios when dealing with dynamic CSS styles.<\/p>\n\n\n\n<p>This way allows you to change the CSS styles for one or multiple elements present in the DOM.<\/p>\n\n\n\n<p>All you have to do is:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Query the element present in the DOM.<\/li>\n\n\n\n<li>And set the style or styles for it one by one.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> element = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'.demo'<\/span>);\nelement.style.backgroundColor = <span class=\"hljs-string\">'red'<\/span>;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Notice that when setting the CSS styles using the <code>style<\/code> property you have to write the CSS properties in camelcase. Instead of using a dash <code>-<\/code> to separate the words you will have to write in capitals the first letter of each word. (<code>backgroundColor<\/code>, <code>fontSize<\/code>)<\/p>\n<\/blockquote>\n\n\n\n<p>If you execute this code just like this, you&#8217;ll notice the change takes place on page load.<\/p>\n\n\n\n<p>If you want to change the CSS styles dynamically you&#8217;ll have to attach this portion of code to some event.<\/p>\n\n\n\n<p>For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the <code>click<\/code> event and attach a function containing the previous code.<\/p>\n\n\n\n<p>Here&#8217;s an example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> button = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'button'<\/span>);\nbutton.addEventListener(<span class=\"hljs-string\">'click'<\/span>, () =&gt; {\n    <span class=\"hljs-keyword\">const<\/span> element = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'.demo'<\/span>);\n    element.style.backgroundColor = <span class=\"hljs-string\">'red'<\/span>;\n});\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_popwJdg\" data-src=\"\/\/codepen.io\/anon\/embed\/popwJdg?height=450&amp;theme-id=1&amp;slug-hash=popwJdg&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed popwJdg\" title=\"CodePen Embed popwJdg\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Note that when you apply specific styles using JavaScript, these styles have precedence over the styles applied externally on a stylesheet and even to the ones applied inline, in the HTML element itself.<\/p>\n<\/blockquote>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-class\">.demo<\/span>{\n    <span class=\"hljs-attribute\">color<\/span>: red;\n}\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"hljs-comment\">&lt;!-- Element with inline styles declared in the HTML --&gt;<\/span>\n<span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">class<\/span>=<span class=\"hljs-string\">\"demo\"<\/span> <span class=\"hljs-attr\">style<\/span>=<span class=\"hljs-string\">\"color: blue;\"<\/span>&gt;<\/span>Demo<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this case, for instance, we have an element with an inline style providing it with a yellow background.<\/p>\n\n\n\n<p>If we now set the CSS <code>color<\/code> property to <code>green<\/code> using JavaScript, then our element will get a <code>green<\/code> color. It will overwrite the inline style and the style applied on the external CSS stylesheet.<\/p>\n\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_jOYwPYP\" data-src=\"\/\/codepen.io\/anon\/embed\/jOYwPYP?height=450&amp;theme-id=1&amp;slug-hash=jOYwPYP&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed jOYwPYP\" title=\"CodePen Embed jOYwPYP\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"2.-set-multiple-css-styles-at-the-same-time\">2. Set Multiple CSS Styles At The Same Time<\/h2>\n\n\n<p>Imagine you have to apply, let&#8217;s say 5 or 10 styles for a single element.<\/p>\n\n\n\n<p>You can go one by one and have something like the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">element.style.display = <span class=\"hljs-string\">'block'<\/span>;\nelement.style.width = <span class=\"hljs-string\">'100px'<\/span>;\nelement.style.backgroundColor = <span class=\"hljs-string\">'red'<\/span>;\nelement.style.border = <span class=\"hljs-string\">'2px'<\/span>;\nelement.style.fontSize = <span class=\"hljs-string\">'12px'<\/span>;\nelement.style.color = <span class=\"hljs-string\">'white'<\/span>;\nelement.style.margin = <span class=\"hljs-string\">'20px'<\/span>;\nelement.style.paddingLeft = <span class=\"hljs-string\">'10px'<\/span>;\nelement.style.paddingBottom = <span class=\"hljs-string\">'10px'<\/span>;\nelement.style.lineHeight = <span class=\"hljs-string\">'13px'<\/span>;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>But perhaps you are looking for a &#8220;smarter&#8221; way to change them all <strong>at the same<\/strong> time without so much code repetition.<\/p>\n\n\n\n<p>If that&#8217;s the case, then I have good news for you!<\/p>\n\n\n\n<p>You can actually pass a <code>string<\/code> value to the <code>cssText<\/code> property to set multiple CSS styles at once.<\/p>\n\n\n\n<p>Even better,  we can use <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Template_literals\" target=\"_blank\" rel=\"noopener nofollow\">template literals<\/a> kind of strings to keep them separate in different lines as you do in your stylesheets.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-comment\">\/\/ Defining all our CSS styles<\/span>\n<span class=\"hljs-keyword\">const<\/span> myStyles = <span class=\"hljs-string\">`\n    display: block;\n    width: 80%;\n    background-color: red;\n    border: 2px;\n    font-size: 5em;\n    color: white;\n    margin: 20px;\n    padding-left: 10px;\n    padding-bottom: 10px;\n    border: 2px solid black;\n`<\/span>;\n<span class=\"hljs-keyword\">const<\/span> element = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'.demo'<\/span>);\n\nelement.style.cssText = myStyles;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_GRyEJQz\" data-src=\"\/\/codepen.io\/anon\/embed\/GRyEJQz?height=450&amp;theme-id=1&amp;slug-hash=GRyEJQz&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed GRyEJQz\" title=\"CodePen Embed GRyEJQz\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>If you are getting into JavaScript you might want to check <a href=\"https:\/\/alvarotrigo.com\/blog\/best-way-learn-javascript\/\">What&#8217;s The Best Way To Learn JavaScript<\/a>.<\/p>\n<\/blockquote>\n\n\n<h2 class=\"wp-block-heading\" id=\"2.-change-css-class-in-javascript\">2. Change CSS class in JavaScript<\/h2>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">class<\/span>=<span class=\"hljs-string\">\"demo\"<\/span>&gt;<\/span>Hello<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-comment\">\/\/ Adding a CSS class name to an element<\/span>\n<span class=\"hljs-keyword\">const<\/span> element = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'.demo'<\/span>);\nelement.classList.add(<span class=\"hljs-string\">'new-class'<\/span>);\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-class\">.new-class<\/span>{\n    <span class=\"hljs-attribute\">background<\/span>: red;\n}\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In the same way, you can also remove certain classes by using <code>classList.remove<\/code> or even toggle them when using <code>classList.toggle<\/code>.<\/p>\n\n\n\n<p>Here&#8217;s an example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-comment\">\/\/ Removing an existing class from an element<\/span>\n<span class=\"hljs-keyword\">const<\/span> element = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'.demo'<\/span>);\nelement.classList.removeClass(<span class=\"hljs-string\">'.new-class'<\/span>);\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-comment\">\/\/ Toggling a class from an element<\/span>\n<span class=\"hljs-keyword\">const<\/span> element = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'.demo'<\/span>);\nelement.classList.toggleClass(<span class=\"hljs-string\">'.new-class'<\/span>);\n\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_VwyWLbx\" data-src=\"\/\/codepen.io\/anon\/embed\/VwyWLbx?height=450&amp;theme-id=1&amp;slug-hash=VwyWLbx&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed VwyWLbx\" title=\"CodePen Embed VwyWLbx\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"3.-change-css-stylesheets-dynamically\">3. Change CSS stylesheets dynamically<\/h2>\n\n\n<p>Let&#8217;s say that now you do not want to add inline styles to an element or apply a class to it. Instead, you want to apply a change at the stylesheet level. Why?<\/p>\n\n\n\n<p>There are a couple of reasons:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>\n<p>You might want to apply the change to all elements with a certain selector. But not just to the elements present right now on the HTML, but also to all future ones that will be added dynamically later on.<\/p>\n<\/li>\n\n\n\n<li>\n<p>There might be a huge amount of elements sharing the selector you want to apply changes to. Imagine 500 elements sharing your selector, or even 1K, 5K, 10K. Having to select all those elements using JavaScript and then loop through them to change their style (or add a class) will be EXTREMELY slow.<\/p>\n<\/li>\n<\/ol>\n\n\n\n<p>Here&#8217;s where <strong>modifying the CSS stylesheet<\/strong> directly will come on handy.<\/p>\n\n\n\n<p>You can select the stylesheets of a document by using <code>document.styleSheets<\/code>. If you know that the stylesheet you want to modify is the second one, you can get it by using <code>document.styleSheets[2]<\/code>.<\/p>\n\n\n\n<p>Then, you would loop through all its rules and get the one you need to modify. In this case, if you want to modify the <code>.element<\/code> class, you can compare each of the rules&#8217; selector with <code>.element<\/code>.<\/p>\n\n\n\n<p>Here&#8217;s the code:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">\n<span class=\"hljs-comment\">\/\/ Getting the stylesheet<\/span>\n<span class=\"hljs-keyword\">const<\/span> stylesheet = <span class=\"hljs-built_in\">document<\/span>.styleSheets&#91;<span class=\"hljs-number\">2<\/span>];\n<span class=\"hljs-keyword\">let<\/span> elementRules;\n\n<span class=\"hljs-comment\">\/\/ looping through all its rules and getting your rule<\/span>\n<span class=\"hljs-keyword\">for<\/span>(<span class=\"hljs-keyword\">let<\/span> i = <span class=\"hljs-number\">0<\/span>; i &lt; stylesheet.cssRules.length; i++) {\n  <span class=\"hljs-keyword\">if<\/span>(stylesheet.cssRules&#91;i].selectorText === <span class=\"hljs-string\">'.element'<\/span>) {\n    elementRules = stylesheet.cssRules&#91;i];\n  }\n}\n\n<span class=\"hljs-comment\">\/\/ modifying the rule in the stylesheet<\/span>\nelementRules.style.setProperty(<span class=\"hljs-string\">'background'<\/span>, <span class=\"hljs-string\">'blue'<\/span>);\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And here is the Codepen example that you can play with:<\/p>\n\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_zYpzGKo\" data-src=\"\/\/codepen.io\/anon\/embed\/zYpzGKo?height=450&amp;theme-id=1&amp;slug-hash=zYpzGKo&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed zYpzGKo\" title=\"CodePen Embed zYpzGKo\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"4.-append-and-remove-css-stylesheets-dynamically\">4. Append And Remove CSS stylesheets dynamically<\/h2>\n\n\n<p>In some cases, we might want to just append a whole new stylesheet or even replace an existing one.<\/p>\n\n\n\n<p>The reason for it might be:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>\n<p>You have a web application that supports multiple themes and allows the user to change them dynamically.<\/p>\n<\/li>\n\n\n\n<li>\n<p>You might want to package a component in a single JS file instead of having to include both files, the JS and the CSS one.<\/p>\n<\/li>\n<\/ol>\n\n\n\n<p>The way this works is quite simple:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>1- We write the content for our new stylesheet using template literals.<\/li>\n\n\n\n<li>2- We select the <code>head<\/code> element of the page to append our new stylesheet.<\/li>\n\n\n\n<li>3- We create a stylesheet element using <code>document.createElement(\"style\")<\/code><\/li>\n\n\n\n<li>4- We append our stylesheet content to the new style element by using <code>document.createTextNode<\/code> and <code>appendChild<\/code>.<\/li>\n<\/ol>\n\n\n\n<p>Here&#8217;s the code:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">const<\/span> button = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">\"button\"<\/span>);\n\n<span class=\"hljs-comment\">\/\/ The content of the stylesheet<\/span>\n<span class=\"hljs-keyword\">const<\/span> styleSheetContent = <span class=\"hljs-string\">`\n    .demo{\n        background:red;\n    }\n`<\/span>;\n\n<span class=\"hljs-comment\">\/\/ Attaching the change to a click event in a button <\/span>\nbutton.addEventListener(<span class=\"hljs-string\">\"click\"<\/span>, () =&gt; {\n    appendStyleSheet(<span class=\"hljs-string\">\"demo\"<\/span>, styleSheetContent);\n});\n\n<span class=\"hljs-comment\">\/\/ Appends CSS content to the head of the site<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">appendStyleSheet<\/span>(<span class=\"hljs-params\">id, content<\/span>) <\/span>{\n    <span class=\"hljs-keyword\">if<\/span> (!<span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">\"#\"<\/span> + id)) {\n        <span class=\"hljs-keyword\">var<\/span> head = <span class=\"hljs-built_in\">document<\/span>.head || <span class=\"hljs-built_in\">document<\/span>.getElementsByTagName(<span class=\"hljs-string\">\"head\"<\/span>)&#91;<span class=\"hljs-number\">0<\/span>];\n        <span class=\"hljs-built_in\">console<\/span>.log(head);\n        head.appendChild(createStyleElement(id, content));\n    }\n}\n\n<span class=\"hljs-comment\">\/\/ Creates the style element<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">createStyleElement<\/span>(<span class=\"hljs-params\">id, content<\/span>) <\/span>{\n    <span class=\"hljs-keyword\">var<\/span> style = <span class=\"hljs-built_in\">document<\/span>.createElement(<span class=\"hljs-string\">\"style\"<\/span>);\n    style.type = <span class=\"hljs-string\">\"text\/css\"<\/span>;\n    style.id = id;\n\n    <span class=\"hljs-keyword\">if<\/span> (style.styleSheet) {\n        style.styleSheet.cssText = content;\n    } <span class=\"hljs-keyword\">else<\/span> {\n        style.appendChild(<span class=\"hljs-built_in\">document<\/span>.createTextNode(content));\n    }\n    <span class=\"hljs-keyword\">return<\/span> style;\n}\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And here is the Codepen example so you can test it by yourself and modify a few things to your needs:<\/p>\n\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_popwJKy\" data-src=\"\/\/codepen.io\/anon\/embed\/popwJKy?height=450&amp;theme-id=1&amp;slug-hash=popwJKy&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed popwJKy\" title=\"CodePen Embed popwJKy\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"5.-overwrite-css-!important-style-with-javascript\">5. Overwrite CSS <code>!important<\/code> style with JavaScript<\/h2>\n\n\n<p>We all know the rule: <em>&#8220;Avoid using !important&#8221;<\/em>. But hey! Sometimes it&#8217;s really necessary or it is just out of our control.<\/p>\n\n\n\n<p>The <code>!important<\/code> priority property makes sure that such style will be overwriting any inline declared style (written in the HTML element itself) as well as any previously declared rule that applies to your element.<\/p>\n\n\n\n<p>So&#8230; what if we need to overwrite the style that was previously declared using <code>!important<\/code>?<\/p>\n\n\n\n<p>Imagine we have our element:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"HTML, XML\" data-shcb-language-slug=\"xml\"><span><code class=\"hljs language-xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">class<\/span>=<span class=\"hljs-string\">\"demo\"<\/span>&gt;<\/span>Demo<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">HTML, XML<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">xml<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And the stylesheet using the <code>!important<\/code> rule like so:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-class\">.demo<\/span>{\n    <span class=\"hljs-attribute\">background-color<\/span>: yellow <span class=\"hljs-meta\">!important<\/span>;\n}\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>All you have to do is apply the <code>priority<\/code> parameter on the <code>setProperty<\/code> function that JavaScript provides us:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">el.style.setProperty(property, value, priority);\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here&#8217;s an example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-keyword\">var<\/span> el = <span class=\"hljs-built_in\">document<\/span>.querySelector(<span class=\"hljs-string\">'.demo'<\/span>);\nel.style.setProperty(<span class=\"hljs-string\">'background-color'<\/span>, <span class=\"hljs-string\">'red'<\/span>, <span class=\"hljs-string\">'important'<\/span>);\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Notice how when using <code>setProperty<\/code> we specify the CSS properties exactly in the same way we do in our stylesheet. Using a dash <code>-<\/code> to separate the words. (<code>background-color<\/code>, <code>font-size<\/code>)<\/p>\n<\/blockquote>\n\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_dyJRorg\" data-src=\"\/\/codepen.io\/anon\/embed\/dyJRorg?height=450&amp;theme-id=1&amp;slug-hash=dyJRorg&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed dyJRorg\" title=\"CodePen Embed dyJRorg\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n<p><!-- ## 6. Change CSS variables using JavaScript\n\n\n```js\nel.style.setProperty('--my-var', 200 + 'px');\n```\n\nHere's a full example:\n\n```js\n\n\n```\n<\/p>\n\n\n<\/p>\n\n\n<div class=\"wp-block-cp-codepen-gutenberg-embed-block cp_embed_wrapper\"><iframe id=\"cp_embed_undefined\" data-src=\"\/\/codepen.io\/anon\/embed\/undefined?height=450&amp;theme-id=1&amp;slug-hash=undefined&amp;default-tab=js,result\" height=\"450\" scrolling=\"no\" frameborder=\"0\" allowfullscreen allowpaymentrequest name=\"CodePen Embed undefined\" title=\"CodePen Embed undefined\" class=\"cp_embed_iframe lazyload\" style=\"width:100%;overflow:hidden\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" data-load-mode=\"1\">CodePen Embed Fallback<\/iframe><\/div>\n\n\n<p>--&gt;<br \/>\n<!-- ## 7. Change CSS on Pseudo Element --><br \/>\n<!-- \n## FAQs\n\n### Why Changing CSS With JavaScript?\n\n### How To Link The CSS To The HTML?\n\n### How To Combine HTML, CSS and JavaScript?\n\n### What are the 3 types of CSS?\n\n## Related Articles --><\/p>\n\n<h2 class=\"wp-block-heading\" id=\"references%3A\">References:<\/h2>\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/CSSStyleDeclaration\/setProperty\" rel=\"noopener noreferrer nofollow\" target=\"_blank\">MDN Web Docs<\/a><\/li>\n<\/ul>\n\n\n<h2 class=\"wp-block-heading\" id=\"related-articles%3A\">Related Articles:<\/h2>\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/alvarotrigo.com\/blog\/javascript-alert\/\">How To Use JavaScript Alert<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/alvarotrigo.com\/blog\/javascript-select-option\/\">How To Change Selected Option in JavaScript<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/alvarotrigo.com\/blog\/prevent-scroll-on-scrollable-element-js\/\">How To Prevent Scroll On Scrollable Elements<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/alvarotrigo.com\/blog\/css-alerts\/\">Pure CSS Alerts<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>We show you 5 ways to modify the CSS style using JavaScript. Learn how to change inline and external styles and how to do it in the best way possible for each case.<\/p>\n","protected":false},"author":1,"featured_media":4797,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[107],"tags":[9,10,17],"class_list":["post-4798","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","tag-css","tag-javascript","tag-web"],"acf":[],"_links":{"self":[{"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/posts\/4798","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/comments?post=4798"}],"version-history":[{"count":4,"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/posts\/4798\/revisions"}],"predecessor-version":[{"id":18974,"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/posts\/4798\/revisions\/18974"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/media\/4797"}],"wp:attachment":[{"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/media?parent=4798"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/categories?post=4798"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/alvarotrigo.com\/blog\/wp-json\/wp\/v2\/tags?post=4798"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}