How to Change CSS with JavaScript? Full Guide

Photo of author

You may have changed CSS using a style.css or <style> tag. But have you ever thought about how to change CSS with other methods? This article will deal with how to change CSS with JavaScript in detail.

There are eight ways to change CSS in JavaScript:

  • Using CSS inline properties.
  • Add Multiple CSS Styles.
  • Make changes in the CSS class.
  • Change CSS stylesheets.
  • Include and remove CSS stylesheets.
  • Rewrite CSS !important style. 
  • Changing through HTML attributes
  • Change using CSSOM

You can do many things with JavaScript, like leveraging JavaScript libraries to create table borders without CSS and using list filters in JavaScript, etc. If you face difficulty using the abovementioned methods, you are in the right place. We will delve deep into these eight methods and help you to understand them via examples. 

See Also: 7 HTML CSS Projects For Beginners To Start Web Development

8 Ways To Change CSS with JavaScript

These are eight ways to change CSS with JavaScript. Without further ado, let’s discuss them in detail.

Use inline CSS Properties

The first solution on how to change CSS with JavaScript is to use inline CSS properties. Moreover, this is the most common technique developers use to style a specific element.

css inline

For this, you have to run a query and style it. But what will happen is the changes will take place after the page is loaded. We will attach a button to the query to see the changes immediately. Let’s discuss an example in detail to understand how it works.

Example

First, let’s start with the query and then style it. The code for this will be

const element = document.querySelector(‘.demo’);

element.style.backgroundColor = ‘blue’;

In addition, we have to attach a button now to see the changes immediately. Let’s look at the code below: 

const button = document.querySelector(‘button’);

button.addEventListener(‘click’, () => {

    const element = document.querySelector(‘.demo’);

    element.style.backgroundColor = ‘blue’;

});

Furthermore, if you write this code, you will see that a button is attached. Upon clicking it, the color will change to blue. This is the first solution on how to change CSS using JavaScript with inline CSS property.

Add Multiple CSS Styles

Sometimes, you want to add multiple styles, but it consumes much time. By using JavaScript, you can add various CSS styles instantly. The easiest way to do this is to pass a string with a CSS property, and you are all set. Let’s discuss this in detail with an example to understand the concept.

using css

Example

Let’s discuss how you can add multiple styles without the string. The code would look like

element.style.display = ‘block’;

element.style.width = ‘120px’;

element.style.backgroundColor = ‘green’;

element.style.border = ‘4px’;

element.style.fontSize = ’12px’;

element.style.color = ‘white’;

element.style.margin = ’20px’;

element.style.paddingLeft = ’10px’;

element.style.paddingBottom = ’10px’;

element.style.lineHeight = ’13px’;

Moreover, you have to write a lot in this code. Now, let’s use a string: 

const button = document.querySelector(“button”);

button.addEventListener(“click”, changeMultipleCSS);

function changeMultipleCSS(e) {

  // Adding all our CSS styles

  const myStyles = `

    display: block;

    width: 60%;

    background-color: green;

    border: 2px;

    font-size: 5em;

    color: white;

    margin: 20px;

    padding-left: 10px;

    padding-bottom: 10px;

    border: 2px solid black;

  `;

  const element = document.querySelector(“.demo”);

  element.style.cssText = myStyles;

}

Remember that we will attach a button to every example to understand each concept. Furthermore, this is another solution to change CSS with JavaScript.  

Make changes in the CSS Class

Another solution to change CSS in JavaScript is to modify the CSS class. You can add, remove, and toggle classes with JavaScript’s help. This is one of the easiest methods that developers use, which we will understand in detail through an example. 

login page in html with css code

Example

Let’s start by creating a div in HTML like this:

<div class=”tutorial”>Hey</div>

Now, we will write a code in JS to add a class like:

// Adding a CSS class name to an element

const element = document.querySelector(‘.tutorial’);

element.classList.add(‘new-class’);

Furthermore, we will set the CSS for the class that we added:

.new-class{

    background: blue;

}

In this way, you can add a class with JavaScript. For removing or toggling a class, you can use classList.remove and classList.toggle. For example

// Removing an existing class from an element

const element = document.querySelector(‘.tutorial’);

element.classList.removeClass(‘.new-class’);

// Toggling a class from an element

const element = document.querySelector(‘.tutorial’);

element.classList.toggleClass(‘.new-class’);

Change CSS Stylesheets

Another solution on how to change CSS style in JavaScript is to modify the stylesheets dynamically. Modifying the stylesheet is used because sometimes developers want to add different styles to a particular element with the same selector that is applied to all the selectors. We can achieve this by first selecting the stylesheet, looping all the rules, and setting it the way you want. Let’s understand this in detail.

javascript code

Example

First, we have to get the stylesheet. For this, you can write:

// Getting the stylesheet

const stylesheet = document.styleSheets[2];

let elementRules;

Now, loop all the rules and set it like this:

// looping through all its rules and getting your rule

for(let i = 0; i < stylesheet.cssRules.length; i++) {

  if(stylesheet.cssRules[i].selectorText === ‘.element’) {

    elementRules = stylesheet.cssRules[i];

  }

}

Change the rule in the stylesheet like:

// modifying the rule in the stylesheet

elementRules.style.setProperty(‘background’, ‘green’);

Include and Remove Stylesheets

Another solution on how to change CSS with JavaScript is to include and remove stylesheets. You might have noticed some of the websites have a light mode and a dark mode, which is basically done by using this principle. If you want to include a different stylesheet, you have to use template literals for the content of the stylesheet you want to include.

css stylesheet code

Furthermore, attach the stylesheet in the head element. Now, use a document.createElement(“style”) to make the stylesheet and include the content using document.createTextNode and appendChild. Let’s understand this with an example in detail.

Example

The JavaScript code for this will be:

const button = document.querySelector(“button”);

// The content of the stylesheet

const styleSheetContent = `

    .demo{

        background:green;

    }

`;

// Attaching the change to a click event in a button 

button.addEventListener(“click”, () => {

    appendStyleSheet(“demo”, styleSheetContent);

});

// Appends CSS content to the head of the site

function appendStyleSheet(id, content) {

    if (!document.querySelector(“#” + id)) {

        var head = document.head || document.getElementsByTagName(“head”)[0];

        console.log(head);

        head.appendChild(createStyleElement(id, content));

    }

}

// Creates the style element

function createStyleElement(id, content) {

    var style = document.createElement(“style”);

    style.type = “text/css”;

    style.id = id;

    if (style.styleSheet) {

        style.styleSheet.cssText = content;

    } else {

        style.appendChild(document.createTextNode(content));

    }

    return style;

}

Rewrite CSS !important style

You can also use !important to change the CSS with JavaScript. But what is !important? As the name suggests, it is something important. When you use !important property, it overwrites any inline style, giving preference to the property. But how do we overwrite an element that is already used with an !important property? Let’s discuss this in detail.

!important css style

Example 

Let’s say we have a div in HTML like

<div class=”tutorial”>tutorial</div>

The CSS property is:

.tutorial{

    background-color: green !important;

}

To overwrite this you can write:

el.style.setProperty(property, value, priority);

For example:

var el = document.querySelector(‘.tutorial’);

el.style.setProperty(‘background-color’, ‘green’, ‘important’);

This way you can now also overwrite the !important property easily. 

Change by HTML Attributes

Changing CSS by modifying HTML attributes is one of the most basic methods that you will come across. Moreover, you just have to use the document.getElementById. Let’s understand this in detail with an example. 

html doctype code

Example

Let’s look at the HTML code:

<div id=”myElement” style=”color: green;”>Hello Developers</div>

<script>

  var myElement = document.getElementById(“myElement”);

  myElement.setAttribute(“style”, “color: blue; font-size: 20px;”);

</script>

In this way, you can change any CSS property by directly changing the HTML attributes.

Make changes using CSSOM

Another solution on how to change CSS variables in JavaScipt is to modify using CSSOM. CSSOM stands for CSS object model and is used to eradicate third-party styles instead of something new.

cssom and dom

You can use it in many ways, but we will use this to change the stylesheet rule. Let’s discuss an example to understand how CSSOM can be applied.

Example

The code mentioned below will focus on changing the background color using CSSOM.

<html lang=”en”>

  <head>

    <title>Modifying a stylesheet rule with CSSOM</title>

    <style>

      body {

        background-color: green;

      }

    </style>

    <script>

      const stylesheet = document.styleSheets[0];

      stylesheet.cssRules[0].style.backgroundColor = “red”;

    </script>

  </head>

  <body>

    The stylesheet declaration for the body’s background color is modified via

    JavaScript.

  </body>

</html>

FAQs

Can I change the CSS variable in JavaScript?

The setProperty() method can change the CSS variable in JavaScript.

Can you change CSS with JavaScript?

JavaScript is one of the advanced languages through which you can modify CSS properties on any webpage.

How to change the CSS dynamically in JavaScript?

You can write element. style. color = 'orange'; to change the CSS dynamically in JavaScript.

How to change body CSS with JavaScript?

The document. body property can be used to change the body CSS with JavaScript. For example: document. body. style. backgroundColor = 'red'

Conclusion

In conclusion, we found eight ways through which you can change CSS using JavaScript. You can also try different techniques like sorting in JavaScript and number formatting in JavaScript to increase your understanding and try out other programming languages that will make you a skilled developer. Many people prefer Typescript over JavaScript. So before selecting any of these languages, do JavaScript vs Typescript research to understand what will be easy for you. 

See Also: Change CSS Styles Using JS: Dynamic Styling For Modern Websites

Leave a Comment