javascripthtmlhtml5-audiocode-cleanupgetelementsbyname

HTML5 Audio Player: How to select by HTML elements instead of div ID's?


Making an html5 player, I'm moving away "from divs with id's" towards "simple html elements".

Old Situation (works)

<audio src="track1.mp3" id="audio"></audio>
<controls>
    <play id="play" style="display:none">PLAY</button>
    <pause id="pause" style="display:none">PAUSE</button>
    <div id="progress"><div id="bar"></div></div>
</controls>

Javascript gets elements by divs with an id

var myAudio = document.getElementById('audio');
var play = document.getElementById('play');
var pause = document.getElementById('pause');
... etc

Desired Situation (doesn't work fully)

<audio src="track1.mp3"></audio>
<controls>
    <play style="display:none">PLAY</play>
    <pause style="display:none">PAUSE</pause>
    <progress><bar></bar></progress>
</controls>

Updated Javascript, after help of @grateful & @Nathan Montez works partially

var myAudio = document.getElementsByTagName('audio')[0];
var play = document.getElementsByTagName('play')[0];
var pause = document.getElementsByTagName('pause')[0];
... etc

In the new version the progress bar does not work! What have we overlooked? Thanks!


Solution

  • document.getElementsByTagName('audio') will return an array, even if it only has a length of 1. You need to do this:

    document.getElementsByTagName('audio')[0];