JAVASCRIPT
Programmatically Modifying Element CSS Styles
Discover how to dynamically change an element's inline CSS properties like color, font-size, or display using JavaScript's `style` object.
// Get a reference to the element you want to style
const myElement = document.getElementById('styledElement');
if (myElement) {
// Set individual CSS properties directly
myElement.style.color = '#ff4500'; // OrangeRed
myElement.style.fontSize = '20px';
myElement.style.fontWeight = 'bold';
myElement.style.backgroundColor = '#f0f0f0';
myElement.style.border = '2px solid #ff4500';
myElement.style.padding = '15px';
myElement.style.transition = 'all 0.3s ease-in-out'; // For smooth transitions
// Toggle display property
let isVisible = true;
setInterval(() => {
if (isVisible) {
myElement.style.opacity = '0'; // Use opacity for smooth hide
setTimeout(() => myElement.style.display = 'none', 300); // Hide after transition
} else {
myElement.style.display = 'block';
setTimeout(() => myElement.style.opacity = '1', 10); // Show and fade in
}
isVisible = !isVisible;
}, 2000); // Every 2 seconds
}
// Example of HTML structure:
/*
<p id="styledElement">Hello, I will be styled dynamically!</p>
*/
How it works: This code demonstrates how to directly manipulate an element's inline CSS styles using JavaScript. By accessing the `style` property of a DOM element, you can set individual CSS properties (e.g., `color`, `fontSize`, `backgroundColor`) just like you would in a CSS stylesheet, but using camelCase for property names. The snippet also includes an example of toggling an element's visibility with a smooth fade effect using `opacity` and `display` properties.