How to change the CSS style of an HTML element using JavaScript?

To change the CSS style of an HTML element using JavaScript, you can use the style property of the element. Here is an example:

  1. First, select the HTML element to modify. You can use various methods like getElementById, getElementsByClassName, or querySelector.
var element = document.getElementById("myElement");
  1. Manipulate the CSS properties of the selected element using the style property. You can access and modify any CSS property of the element using .style.propertyName.
element.style.backgroundColor = "red";
  1. You can change multiple CSS properties in one line by chaining the .style properties:
element.style.backgroundColor = "red"; element.style.width = "200px"; element.style.color = "white";

Note: In JavaScript, CSS properties are written in camel case. For example, background-color becomes backgroundColor, font-size becomes fontSize, etc.

Combining all the steps, here is an example changing the background color of an element with the ID "myElement" to red:

<!DOCTYPE html> <html> <head> <style> #myElement { background-color: blue; width: 100px; height: 100px; } </style> </head> <body> <div id="myElement"></div> <script> var element = document.getElementById("myElement"); element.style.backgroundColor = "red"; </script> </body> </html>

In the above example, the element initially has a background color of blue, and the JavaScript code changes it to red.