If you're trying to target the `audio` tag within each `td`, but are lacking a unique identifier, there's a simple solution. By making a small addition to your code, you can easily address this issue.
<td id="A" class="squareA" type="button";>
<audio id="audio-A">
<source src="music/work_it.wav" type="audio/wav">
</audio>
Work It
</td>
By using specific `id`s, you can now locate each tag effortlessly.
Alternatively, if you include `controls` in the `audio` tag, users will be able to activate the default browser player and play the file without any additional coding.
<audio controls>
<source ... etc
</audio>
However, if `controls` are absent (or set to `controls="false"`), the default browser player won't appear. If your goal is to play the audio file with a click event, this may be the desired outcome.
At this point, the `id`s of Audio tags might not be useful because without `controls`, nothing will be displayed for users to interact with. In such cases, you would need to target all of their respective `td` elements in the table.
If you haven't already done so, consider adding an `id` attribute to the audio table (e.g., 'audio-table'), allowing you to use `.addEventListener()` on each `td` box with a function called upon page loading:
function addEvents2Table() {
/* assuming the table has an
id of 'audio-table' here */
var audioTable = document.getElementById('audio-table');
/* collect td tags */
var tdTags = audioTable.getElementsByTagName('td');
var len = tdTags.length;
/* add a 'playAudio' function call
to each td when clicked */
while(len--) {
tdTags[len].addEventListener(
'click', playAudio, false
);
}
}
/* trigger 'addEvents2Table()' on page load */
window.onload = function() {
addEvents2Table();
};
Now, when a `td` in the table is clicked, the `playAudio()` function will execute. All that remains is to define this function based on your HTML structure:
In the first code snippet provided above, an `id` was added to the audio tag within a td-tag with an `id` of "A." This initial setup will prove valuable now:
function playAudio(event) {
/* fetch the 'id' of the clicked element */
var tagID = event.target.id;
/* append it to 'audio-' */
var audioID = 'audio-' + tagID;
/* locate the corresponding audio tag */
var audioTAG = document.getElementById(audioID);
/* initiate playback */
audioTAG.play();
}
There are various considerations to bear in mind moving forward. Are you comfortable with simultaneous audio playback in the browser? Would you like users to stop an audio clip? As currently implemented, clicking multiple boxes rapidly could result in overlapping audio playback attempts. Additionally, clicking a box while its corresponding audio is playing may create issues.
Nevertheless, these suggestions should provide a solid starting point. Feel free to leave a comment if further explanation is needed.
For reference, here is MDN's audio tag page.