Learn how to change CSS styles of elements using JavaScript to create dynamic and interactive web pages.
In this section, we will explore how to modify the styles of HTML elements directly using JavaScript. This capability allows us to create dynamic and interactive web pages that respond to user actions. By the end of this section, you’ll understand how to use JavaScript to change the appearance of elements on your web page, enhancing user experience and engagement.
style
PropertyThe style
property in JavaScript provides a way to access and modify the inline styles of an HTML element. Inline styles are those defined directly on an element using the style
attribute in HTML. When you use JavaScript to change styles, you’re essentially altering these inline styles.
style
PropertyLet’s start with a simple example. Suppose we have a paragraph element on our web page, and we want to change its text color to red using JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modify Styles with JavaScript</title>
</head>
<body>
<p id="myParagraph">This is a paragraph.</p>
<script>
// Select the paragraph element
const paragraph = document.getElementById('myParagraph');
// Change the text color to red
paragraph.style.color = 'red';
</script>
</body>
</html>
In this example, we first select the paragraph element using document.getElementById()
. Then, we use the style
property to set the color
property to 'red'
. This changes the text color of the paragraph to red.
When working with CSS properties in JavaScript, it’s important to understand the camelCase notation. In CSS, properties are typically written in kebab-case (e.g., background-color
). However, in JavaScript, these properties are written in camelCase (e.g., backgroundColor
).
Here are some common CSS properties and their JavaScript equivalents:
background-color
becomes backgroundColor
font-size
becomes fontSize
margin-top
becomes marginTop
Let’s see how we can use camelCase notation to modify multiple styles of an element:
// Select the element
const element = document.getElementById('myElement');
// Change multiple styles
element.style.backgroundColor = '#f0f0f0';
element.style.fontSize = '20px';
element.style.marginTop = '10px';
One of the powerful features of JavaScript is the ability to change styles dynamically based on user interactions or other conditions. This allows you to create interactive and responsive web pages.
Let’s create a button that changes the background color of a div element when clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Style Change</title>
</head>
<body>
<div id="colorBox" style="width: 100px; height: 100px; background-color: blue;"></div>
<button id="changeColorButton">Change Color</button>
<script>
// Select the elements
const colorBox = document.getElementById('colorBox');
const button = document.getElementById('changeColorButton');
// Add a click event listener to the button
button.addEventListener('click', () => {
// Change the background color of the div
colorBox.style.backgroundColor = 'green';
});
</script>
</body>
</html>
In this example, we have a div element with an initial background color of blue. When the button is clicked, we change the background color to green using the style
property.
While modifying styles directly with JavaScript is powerful, it has some limitations:
style
property only affects inline styles. It does not change styles defined in external or internal stylesheets.In many cases, it is more efficient to add or remove CSS classes rather than modifying styles directly. This approach allows you to define styles in a stylesheet and apply them by toggling classes.
Let’s modify the previous example to use classes instead of direct style changes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Classes</title>
<style>
.blue {
background-color: blue;
}
.green {
background-color: green;
}
</style>
</head>
<body>
<div id="colorBox" class="blue" style="width: 100px; height: 100px;"></div>
<button id="changeColorButton">Change Color</button>
<script>
// Select the elements
const colorBox = document.getElementById('colorBox');
const button = document.getElementById('changeColorButton');
// Add a click event listener to the button
button.addEventListener('click', () => {
// Toggle between blue and green classes
if (colorBox.classList.contains('blue')) {
colorBox.classList.remove('blue');
colorBox.classList.add('green');
} else {
colorBox.classList.remove('green');
colorBox.classList.add('blue');
}
});
</script>
</body>
</html>
In this example, we define two classes, .blue
and .green
, in the stylesheet. We then toggle these classes on the div element when the button is clicked. This approach is more maintainable and leverages the power of CSS.
Now that you understand how to modify styles directly and use classes, let’s encourage some experimentation. Try changing different styles, such as font size, border, or padding, and see how they affect the appearance of elements on your page.
display
property.To better understand how style changes affect the DOM, let’s visualize the process using a Mermaid.js diagram.
graph TD; A[HTML Element] --> B{JavaScript} B --> C[style Property] C --> D[Inline Styles] D --> E[Rendered Styles]
Diagram Description: This diagram illustrates how JavaScript interacts with the style
property to modify inline styles, which are then rendered by the browser.
To deepen your understanding of modifying styles with JavaScript, consider exploring the following resources:
To reinforce your learning, try answering the following questions:
style
property?style
property allows you to modify the inline styles of an element using JavaScript.