Sobes.tech
Junior

How can styles be dynamically changed on a web page element?

sobes.tech AI

Answer from AI

You can use the following approaches:

  • Changing the style property of an element: The simplest way, directly modifies inline styles.
    const element = document.getElementById('myElement');
    element.style.color = 'red';
    element.style.fontSize = '20px';
    
  • Adding/removing CSS classes: A more flexible approach based on predefined styles in CSS. Style changes occur by applying or removing classes.
    const element = document.getElementById('myElement');
    element.classList.add('active'); // adds 'active' class
    element.classList.remove('inactive'); // removes 'inactive' class
    element.classList.toggle('visible'); // toggles 'visible' class
    
    In CSS:
    .active {
        background-color: yellow;
    }
    .inactive {
        display: none;
    }
    .visible {
        opacity: 1;
    }
    
  • Changing CSS variables (CSS Custom Properties): Allows changing the values of variables used in CSS, affecting styles of many elements at once.
    const root = document.documentElement;
    root.style.setProperty('--main-color', 'blue');
    
    In CSS:
    :root {
        --main-color: #333;
    }
    .my-element {
        color: var(--main-color);
    }
    
  • element.setAttribute('style', '...'): Less recommended compared to element.style, as it overwrites all inline styles.
    const element = document.getElementById('myElement');
    element.setAttribute('style', 'color: green; border: 1px solid black;');
    
  • Creating and inserting a <style> element: Allows dynamically adding new CSS rules to the page.
    const style = document.createElement('style');
    style.innerHTML = '#myElement { background-color: lightblue; }';
    document.head.appendChild(style);
    
  • Modifying style sheets (document.styleSheets): Direct interaction with Style Sheet objects. Considered more complex and less common in everyday development.

The choice of method depends on the task: element.style is convenient for small, targeted changes; classes are preferable for managing states and complex styles; CSS variables are good for themes and global settings.