DOM CSS
JavaScript can manipulate the CSS of HTML elements dynamically by modifying the style property or by working with CSS classes. This allows for responsive and interactive designs.
Key Topics
- Modifying Styles
- Adding and Removing Classes
- Working with cssText
- JavaScript Usage in DOM
- Key Takeaways
Modifying Styles
The style property allows you to set inline styles directly on an element.
const element = document.getElementById("demo");
element.style.color = "blue";
element.style.fontSize = "20px";
Output
(The text color of the element changes to blue, and the font size becomes 20px.)
Explanation: The style property allows you to apply individual CSS properties directly to the selected element.
Adding and Removing Classes
Use the classList property to add, remove, or toggle classes dynamically.
const element = document.getElementById("demo");
element.classList.add("highlight");
element.classList.remove("hidden");
element.classList.toggle("active");
Output
(The element gains the 'highlight' class, loses the 'hidden' class, and toggles the 'active' class.)
Explanation: The classList property provides methods to manage an element's class list efficiently.
Working with cssText
The cssText property lets you set multiple CSS properties as a single string.
const element = document.getElementById("demo");
element.style.cssText = "color: green; font-weight: bold; background-color: yellow;";
Output
(The text becomes green, bold, and is displayed on a yellow background.)
Explanation: The cssText property allows you to apply multiple styles in one step, replacing any existing inline styles.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating CSS manipulation using JavaScript.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: lightblue;
}
</style>
</head>
<body>
<p id="demo">This is a paragraph.</p>
<button onclick="updateStyles()">Update Styles</button>
<script>
function updateStyles() {
const element = document.getElementById("demo");
element.style.color = "red";
element.classList.add("highlight");
}
</script>
</body>
</html>
Key Takeaways
- Inline Styles: Use the
styleproperty for quick CSS updates. - Class Management: Use
classListto add, remove, or toggle CSS classes. - cssText: Apply multiple styles simultaneously using the
cssTextproperty. - Dynamic Styling: JavaScript allows for interactive and responsive style updates.