Search code examples
javascripthtmlhtml5-audio

Play all audio elements on a HTML page using Javascript


So I have a button that you can click to play every single audio element on the page, but they way it does it is not very good, it uses getElementById for every single element. My page has many audio elements and more are getting added, so I want to get this over with before this problem gets out of hand.

document.getElementById("sound1").play();
document.getElementById("sound2").play();
document.getElementById("sound3").play();
document.getElementById("sound4").play();
document.getElementById("sound5").play();
document.getElementById("sound6").play();
// more code here: https://github.com/3kh0/3kh0.github.io/blob/main/projects/soundboard/index.html

I can use jQuery, but I am trying not to, so a plain JavaScript solution would be nice.


Solution

  • As per your question of targeting all audio elements on a page, the following code will do that for you :

    // create a HTMLCollection of audio elements in constant els
    const els = document.getElementsByTagName("AUDIO");
    // use Array.from() method to convert els to array,
    //   then iterate over it
    Array.from(els).forEach((el) => {
        el.play();
    });
    

    The same functionality could also be used to only play select groups of audio elements. One could use class names for this purpose, or data-attributes.

    For example, all audio elements created like this ...

    <audio controls class="group-one" data-group="one">
        <source src="file.mp3" type="audio/mpeg">
    </audio>
    

    ... could then be added to the HTMLCollection (in the case of getElementsByClassName) or NodeList (when using querySelectorAll) like this ...

    const els = document.getElementsByClassName("group-one");    
    // OR
    const els = document.querySelectorAll('audio[data-group="one"]');