JAVASCRIPT
Toggling Element Visibility with JavaScript Styles
Discover how to dynamically show or hide HTML elements by directly manipulating their CSS `display` property using JavaScript.
const toggleElement = document.getElementById('myToggleElement');
function toggleVisibility() {
if (toggleElement.style.display === 'none') {
toggleElement.style.display = 'block'; // Or 'flex', 'grid', 'inline-block' etc.
} else {
toggleElement.style.display = 'none';
}
}
// Example usage: call this function on a button click
// document.getElementById('toggleButton').addEventListener('click', toggleVisibility);
How it works: This snippet provides a function to toggle the visibility of an HTML element. It checks the element's current `display` style property. If it's 'none', it sets it to 'block' (or another appropriate display value); otherwise, it sets it to 'none', effectively hiding or showing the element on the page.