Skip to main content

How to Change CSS with JavaScript

HTML and CSS are the base on which all websites in the WWW have been made since the inception of the Internet. Even JavaScript has been around for decades but with the advancement in technology and refinement of User-Interface designs, it has become all the more important for the modern Web2.0 websites that have a tight and seamless server-side and client-side interaction.

In today's article, we'll be learning about using JavaScript to change the CSS properties of HTML elements. There are many ways to change the styling of an element using JavaScript and depending on certain things, which we'll get to later, you might want to use one method over the other. See this article for more CSS tips and tricks.

Let's get started!

How to Get the Element from the DOM?

There are many ways to get the element we' re trying to change the CSS or styling properties of in JavaScript like document.getElementById(), document.getElementsByClassName() and document.querySelector(). For this article we'll be using document.querySelector() as in my opinion it is the most intuitive one.

To get an element with an id element1 we'll have to use the following code:

document.querySelector('#element1');

For a class you can use the following:

document.querySelector('.element1');

Do remember since there can be multiple elements with the same class name, this function will return the first one in the DOM. It is not a good practice to reference an element in JavaScript with class names unless you're trying to reference multiple elements.

With this out of the way let's look at several methods of changing the CSS style of elements with JavaScript

Changing the Inline CSS Properties with JavaScript

Changing the inline style of elements is the most straightforward way to change the CSS with JavaScript. With this method, you can change the styling of any element(s) from JavaScript.

To change the properties of any element first we'll have to query or find the element in the DOM from our code. We'll be using document.querySelector for this as discussed above.

Once we have the element we're looking for we'll change the CSS properties as follows:

const el = document.querySelector('#el');
el.style.color = 'white';
el.style.backgroundColor = 'red';

It is important to note that the CSS properties in JavaScript are in camelCase. So background-color becomes backgroundColor and border-bottom-color becomes borderBottomColor.

Also, the CSS styles changed through JavaScript take precedence over CSS or inline (HTML) styling. Expanding on the above code id the HTML code contains the following:

<h1 id="el" style="background-color: green">
Text
</h1>

With the following CSS styling:

#el {
  background-color: blue;
}

The JavaScript code that we looked at would still be able to change the background-color property despite the element having both CSS and inline styling for the same property. Inline properties take precedence over CSS-defined properties and changing them with JavaScript actually changes the inline CSS attributes in the DOM which is why it overrides both originally defined inline properties and CSS-defined properties. The only exception is when the CSS code has the !important rule. For example, let's slightly modify the CSS styling from our previous example:

#el {
  background-color: blue !important;
}

Now if you run the JavaScript code it wouldn't be able to change the background color. To be able to change such styles where the CSS code has !important modifier defined, we'll have to use the following code:

el.style.setProperty('background-color', 'red', 'important');

The setProperty method takes the name of CSS properties as they are defined in CSS:

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

The following is a complete example that changes the CSS property of an element when we click on a button:

See the Pen Changing the Inline CSS Properties with JavaScript Example 01 by computyng.net (@computyng)

Use This Method with Caution

Directly changing the inline styling is simple and straightforward but it has major drawbacks as your project gets bigger and there are thousands of lines of HTML, CSS styling, and JavaScript. Inline styling, unless you have a specific reason to, is usually discouraged in the favor of CSS styling as mixing styling and HTML makes the code messier and harder to maintain. JavaScript-based inline styling changes also make for a harder time debugging your code.

Another thing, the use of <!important> is also discouraged, it makes your CSS harder to debug. The only exception, I can think of right now is to use it to change a styling that your CMS already has defined. Even, that could be done in a better manner in many cases.

A keen eye could catch the fact that something messy but easy could get the job done, but it will require even messier code to deal with it which would make it a nightmare when you start debugging. In most cases you'll be able to get the same job done by the second method we're now going to discuss next.

Change CSS Styling by Adding or Removing Classes in JavaScript

Using CSS classes to style elements can be considered one of the best practices. In this method, we'll be defining two classes for two different stylings, for the same example discussed in the first method. JavaScript provides the following functions to add, remove or toggle the class of elements.

el.classList.add(className);
el.classList.remove(className);
el.classList.toggle(className);

The first two functions work as you may have guessed and the third one toggles or switches on or off the class. Let's have a look at the full example to better understand this:

See the Pen Change CSS Styling by Adding or Removing Classes in JavaScript by computyng.net (@computyng

Why You Should be Using Classes for Adding or Removing Styling?

Classes are one way of defining the styling of an HTML element in CSS, and as we have learned keeping the styling separate from HTML is something that would save you a lot of headaches in the long run. Furthermore, by changing only the classes (adding, removing, or toggling) in JavaScript we keep the styling part separate from JavaScript as well making it more succinct as well.

Dynamically Changing the Stylesheet

The final method we'll be discussing in order to change the styling of an element is by either adding a new stylesheet or removing an existing one and replacing it with another one.

One use-case of this is if your website supports white and dark mode. When the user selects their preference you just change the stylesheet from, say day-mode.css to night-mode.css and the new styling takes effect. Another useful scenario would be if your website supports multiple themes based on user choice. With this method, you'll be able to change the stylesheet directly changing the complete styling of the page.

Let's see an example:

See the Pen test2 by computyng.net (@computyng)

The example itself is pretty self-explanatory. The most important line is the following:

document.querySelector('#css1').setAttribute('href', 'new-css-url');

This way, like any other element and its attribute, we can change the stylesheet's CSS URL, after which the browser will fetch the new URL and make the appropriate changes in the styling of the page. Quite neat, isn't it!

Conclusion

As we have seen today, there are a variety of ways to accomplish one task - change CSS with JavaScript. Depending on what you're actually trying to accomplish, one method would suit you over the other. Always think outside the box when tackling issues in programming. In certain situations, you would be tempted to even go through a CSS programmatically and change the styling of an element defined in the CSS file, but the question is - is it necessary? In most cases, the answer would be "No". When you think outside the box, you'd find maybe a different way to tackle and solve the issue. I hope this article, would not only provide an immediate solution to your problem but also help you in seeing the bigger picture and avoid writing code that gets the job done but would be hard once the debug session starts!

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

How to Create an HTML Form Linked with MySQL Database in PHP

If you're looking for example code and detailed discussion on how to create an HTML form that stores data in a MySQL database using PHP then this post might be what you're looking for. I assume that you're familiar with basic HTML, CSS, PHP coding, and  MySQL. I am going to divide this small project into two parts: The HTML form itself that takes input from the user and the PHP script that saves it into the database A table that displays the user-added data that has been saved in the database. We'll be dealing with the first part in this tutorial. Again I'd like to break this problem into a few parts so that it's easier for you to understand and probably gives you an insight into how breaking up a problem into smaller chunks can help make things clearer in your mind. Let's think about it, there is an HTML form (that is HTML code), then there is the PHP code that deals with the user-input data, and the MySQL database itself. For this tutorial, we'll b