Search code examples
javascriptdisplaygetelementbyidnonetype

How to hide multiple videos automatically while one is displayed?


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";
    }

Solution

  • 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";
    }