JAVASCRIPT
Toggle Element Visibility and Styling with JavaScript
Master how to dynamically add or remove CSS classes and directly modify an element's inline styles to change its appearance or visibility based on user interaction.
// Assume an HTML element with id 'myElement'
const myElement = document.getElementById('myElement');
if (myElement) {
// 1. Toggle a CSS class to change styles (recommended for complex styling)
// If 'active' class exists, remove it; otherwise, add it.
myElement.classList.toggle('active');
// Example: If 'active' class makes text red, this will toggle red/default.
// 2. Directly modify inline styles (useful for simple, one-off changes)
if (myElement.style.display === 'none') {
myElement.style.display = 'block'; // Show element
myElement.style.backgroundColor = 'lightblue';
} else {
myElement.style.display = 'none'; // Hide element
myElement.style.backgroundColor = ''; // Remove background color
}
// You can also use myElement.style.cssText to set multiple styles at once (less common)
// myElement.style.cssText = 'display: block; background-color: lightgreen;';
}
How it works: This snippet illustrates two primary ways to dynamically alter an element's styling: toggling CSS classes and direct inline style manipulation. Using `classList.toggle()` is generally preferred for managing multiple style changes as it leverages predefined CSS rules. Direct `element.style.property` assignment is useful for simple, specific changes like toggling visibility (`display`) or setting a unique color. Conditional logic helps apply styles based on the element's current state.