JavaScript Lessons

Change CSS Styles With JavaScript: Practical Guide

Learn how to change CSS styles with JavaScript using inline styles, element.style, and classList. Clear examples help you update colors, spacing, and active states on the fly.

Serhat ALPASLAN3 min read

what is a JavaScript class and how is it used?

Changing CSS Style Properties with JavaScript

Changing CSS Style Properties with JavaScript and how to apply them.

CSS is a language used to style HTML tags. For example, you can set the font color of a <p> tag to “black”. However, by changing CSS style properties with JavaScript, you can make your web page’s behavior and appearance dynamic.

There are two ways to change CSS style properties with JavaScript: accessing HTML tags directly or accessing them using class names.

To access HTML tags directly, you use the DOM (Document Object Model). The DOM converts all the HTML tags on your web page into a tree structure, and you can access this tree structure with JavaScript. For example, to change the font color of a <p> tag to “black”, you can use the following code:

document.getElementById("myParagraph").style.color = "black";

However, accessing HTML tags directly is often not recommended. That’s because this method changes only a single tag and reduces your code’s scalability. Instead, changing CSS style properties using class names is a better choice. For example, to change the font color of all <p> tags to “black”, you can use the following code:

document.getElementsByClassName("myClass").style.color = "black";

Changing CSS style properties with JavaScript lets you make your web page’s behavior and appearance dynamic. For example, you can change a form’s background color to green. Likewise, when a button is clicked, you can change the size of an image. These features make your web page interactive and user-friendly.

Another point you need to keep in mind when changing CSS style properties with JavaScript is browser compatibility. There can be some differences between browsers, and some properties may not be supported by browsers. Therefore, you should take browser compatibility into account when changing CSS style properties with JavaScript.

As an example, on a web page, the background color of a div can change when the user hovers over it with the mouse.

var el = document.getElementById("myDiv");
el.onmouseover = function() {
    el.style.backgroundColor = "red";
}
el.onmouseout = function() {
    el.style.backgroundColor = "white";
}

In the example, when the user moves the mouse over the div, the background color changes to red, and when the user moves the mouse outside the div, the background color changes to white.

JavaScript lets you make your page’s behavior and appearance dynamic by changing CSS style properties. However, you should take browser compatibility into account, and changing CSS style properties using class names will be a better choice.

Share it if it helped

Write a comment