JAVASCRIPT

Dynamically Changing CSS Styles and Classes

Discover how to modify an element's inline CSS styles directly using the style property and toggle CSS classes to change its appearance or trigger animations dynamically with JavaScript.

function applyDynamicStylesAndClasses(elementId, color, fontSize, className) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  // Change inline styles
  element.style.color = color;
  element.style.fontSize = fontSize;
  element.style.fontWeight = 'bold'; // Example of another style

  // Add/remove/toggle classes
  element.classList.add('highlight'); // Always add 'highlight'
  element.classList.toggle(className); // Toggle the given class
  // element.classList.remove('old-class'); // Example of removing a class
}

// Example usage:
// Assume 'myElement' is an existing element like: <p id="myElement">Change my style</p>
applyDynamicStylesAndClasses('myElement', 'red', '24px', 'active-state');

// To toggle the class again after some time
setTimeout(() => {
  const myElement = document.getElementById('myElement');
  if (myElement) {
    myElement.classList.toggle('active-state');
    myElement.style.backgroundColor = 'yellow';
  }
}, 2000);
How it works: This snippet illustrates how to dynamically alter an HTML element's visual presentation using JavaScript. It covers two primary methods: directly manipulating `element.style` properties for inline CSS changes, and using the `element.classList` API to add, remove, or toggle CSS classes. Toggling classes is particularly effective for triggering pre-defined styles or CSS transitions/animations, offering a clean separation between behavior and presentation logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs