Hiding and showing HTML elements with JavaScript - traditional vs modern approaches.
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
</body>
</html>
JavaScript can hide HTML elements.
<!DOCTYPE html>
<html lang="en">
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" id="hideBtn">Hide</button>
<button type="button" id="showBtn">Show</button>
<button type="button" id="toggleBtn">Toggle</button>
<script>
const demoText = document.getElementById('demo');
const hideButton = document.getElementById('hideBtn');
const showButton = document.getElementById('showBtn');
const toggleButton = document.getElementById('toggleBtn');
hideButton.addEventListener('click', () => {
demoText.style.display = 'none';
});
showButton.addEventListener('click', () => {
demoText.style.display = 'block';
});
toggleButton.addEventListener('click', () => {
if (demoText.style.display === 'none') {
demoText.style.display = 'block';
} else {
demoText.style.display = 'none';
}
});
</script>
</body>
</html>
JavaScript can hide HTML elements.
const for variables (modern ES6+ syntax)style.display property controls element visibility: 'none' hides, 'block' shows (or use original display value)if/else statements enables smart toggle functionalityblock, inline, flex, etc.)const, addEventListener, and arrow functions follows current best practices💡 Pro Tip:
For better control with CSS transitions and animations, consider using CSS classes with opacity and visibility properties instead of display. This allows smooth fade-in/fade-out effects!
Want to see visibility and opacity in action with smooth transitions?