Changing Styles
JavaScript can dynamically change the appearance of HTML elements by modifying their CSS styles through the DOM.
What is Changing Styles?
Changing styles means modifying the visual appearance of an HTML element using JavaScript.
JavaScript can change properties such as color, backgroundColor, fontSize, display, and more.
Simple Definition
Select an element → Access style → Change CSS property.
JavaScript can access DOM elements and modify their visual styles dynamically.
How JavaScript Changes Styles
Common CSS Properties
color
Changes the text color of an element.
backgroundColor
Changes the background color of an element.
fontSize
Changes the size of text displayed inside an element.
fontWeight
Changes the thickness of text.
display
Controls whether an element is visible or how it participates in layout.
border
Allows JavaScript to modify an element's border style.
Example 1: Change Text Color
The color style property can be changed using JavaScript.
let textColor = "blue";
console.log("Original color:", "black");
textColor = "blue";
console.log("Updated color:", textColor);
Original color: black
Updated color: blue
Example 2: Change Background Color
The backgroundColor property can be used to change an element's background.
let backgroundColor = "white";
backgroundColor = "lightblue";
console.log("Background:", backgroundColor);
Background: lightblue
Example 3: Change Font Size
The fontSize property can be used to change the size of text.
let fontSize = "16px";
fontSize = "24px";
console.log("Font Size:", fontSize);
Font Size: 24px
Example 4: Change Multiple Styles
Multiple style properties can be changed on the same element.
let textColor = "black";
let background = "white";
let size = "16px";
textColor = "blue";
background = "lightgray";
size = "22px";
console.log("Color:", textColor);
console.log("Background:", background);
console.log("Font Size:", size);
Color: blue
Background: lightgray
Font Size: 22px
Important Note
JavaScript Style Syntax
CSS property names written in JavaScript generally use camelCase.
For example:
CSS: background-color
JavaScript: backgroundColor
Real-World Example
A website can dynamically highlight a course, change notification colors, resize text, or visually indicate a selected item.
let status = "Available";
console.log("Status:", status);
status = "Course Started";
console.log("Updated Status:", status);
Status: Available
Updated Status: Course Started
Summary
JavaScript can dynamically change the appearance of HTML elements through the DOM. The style property provides access to individual CSS properties such as color, backgroundColor, fontSize, and fontWeight.