To change the CSS style of an HTML element using JavaScript, you can use the style
property of the element. Here is an example:
getElementById
, getElementsByClassName
, or querySelector
.var element = document.getElementById("myElement");
style
property. You can access and modify any CSS property of the element using .style.propertyName
.element.style.backgroundColor = "red";
.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.