JAVASCRIPT

Toggling CSS Classes and Inline Styles

Discover how to add, remove, or toggle CSS classes and apply inline styles to DOM elements using vanilla JavaScript for dynamic styling.

function toggleElementVisibility(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.classList.toggle('hidden'); // Assuming 'hidden' class has display: none; or opacity: 0;
    }
}

function setElementColor(elementId, color) {
    const element = document.getElementById(elementId);
    if (element) {
        element.style.color = color;
    }
}

// Example usage:
// <p id="myParagraph" class="initial-class">Some text</p>
toggleElementVisibility('myParagraph'); // Adds 'hidden' if not present, removes if present
setElementColor('myParagraph', 'blue'); // Sets inline style color: blue;
How it works: This code illustrates two fundamental ways to change an element's appearance: using `classList.toggle` to add or remove CSS classes for predefined styles (e.g., hiding or showing an element), and directly manipulating `element.style` to apply inline style changes. These techniques are crucial for creating dynamic and responsive user interfaces.

Need help integrating this into your project?

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

Hire DigitalCodeLabs