When building web pages, you may want to dynamically show and hide elements rather than just setting their visibility in the initial HTML. For example, you might have a countdown timer that hides a video player, then shows it when the timer reaches 0. Or perhaps you have multiple elements that should all be hidden on page load. Here’s how to achieve this with clean and scalable JavaScript code.
The Problem
Imagine we have some HTML like this:
<div class="countdown">5 seconds remaining!</div>
<div class="player">
<iframe src="..."></iframe>
</div>
<div class="player">
<video src="..."></video>
</div>
We want:
- Hide BOTH
.player
elements on page load - Show countdown on page load
- When countdown finishes, hide it and show players
We could add style attributes or CSS to handle the initial state. But the dynamic showing and hiding has to happen with JavaScript.
Query All Matching Elements
The first step is selecting elements to show and hide. We can use:
document.getElementById('someId');
…to get a single element by its ID.
Or better yet:
document.querySelectorAll('.player');
To get all elements matching the .player
class.
Iterate to Hide/Show
Once we have all the elements, we can loop through them to hide/show:
// Get all players
const players = document.querySelectorAll('.player');
// Hide each one
players.forEach(player => {
player.style.display = 'none';
});
The same applies for showing them again:
players.forEach(player => {
player.style.display = 'block';
});
This will dynamically show/hide every .player
element, even if new ones are added to the DOM later!
Initial State in HTML/CSS
For simplicity, you may still want to define the initial state in CSS:
.player {
display: none;
}
.countdown {
display: block;
}
And use JS only for dynamic changes on user events
Conclusion
The combination of querySelectorAll
, iteration, and style
changes allows scalable show/hide logic. No matter how many matching elements, they can all be easily hidden, shown, or toggled!
What do you think? Let me know if you have any other questions!