0

Instead of using display="none"; for each video manually, is there an automatic way to do this? So that I don't have to copy/paste the same code.

(P.S. There's 21 videos, going to be hundreds eventually.)

    function showVideo1() {
        document.getElementById('video1').style.display = "block";
        document.getElementById('video2').style.display = "none";
        document.getElementById('video3').style.display = "none";
        document.getElementById('video4').style.display = "none";
        document.getElementById('video5').style.display = "none";
    }

3 Answers3

1

you can create a classe with display="none" and give it to all ur videos if u want to show a video u remove this classe

        document.getElementById('video1').classList.add('hide');
        document.getElementById('video2').classList.remove('hide');
.hide{
 display:none;
}
<div class="hide" id="video1">
    video 1
</div>

<div class="hide" id="video2">
    video 2
</div>
1

First, loop through all the <video> tags to hide them all, then show the video you want to show.

const showVideo = (videoNumber) => {
  document.querySelectorAll('video').forEach((video) => (video.style.display = "none"));
  document.querySelector(`video#video${videoNumber}`).style.display = "block";
}
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
0

Try like this:

function showVideo(videoId) {
    //hide all video
    document.getElementsByTagName('video').style.display = "none";
    //show special video
    document.getElementById(videoId').style.display = "block";
}
Lý Hoài
  • 129
  • 6
  • 1
    This doesn't work because `document.getElementsByTagName(...)` returns an array-like object, so you can't modify properties directly on it, you'd need to use a loop of some kind to do that – Samathingamajig Jul 12 '21 at 14:28