JAVASCRIPT

Toggle Element Visibility with CSS Classes

Efficiently show or hide any DOM element by dynamically adding and removing a CSS class, perfect for interactive UI components and dynamic content display.

function toggleVisibility(elementId, className = 'hidden') {
  const element = document.getElementById(elementId);
  if (element) {
    element.classList.toggle(className);
    console.log(`Toggled class '${className}' on element with ID '${elementId}'.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

// Usage example:
// <div id="myElement" class="some-class hidden">Hello World</div>
// <button onclick="toggleVisibility('myElement')">Toggle</button>
// CSS: .hidden { display: none; }
How it works: This snippet demonstrates how to toggle a CSS class on a DOM element using `classList.toggle()`. This is an efficient way to control an element's visibility or style based on its state, allowing CSS to define the visual changes. The function accepts an element ID and an optional class name, making it versatile for various UI interactions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs