I have a table of records, some of those records will have an image in a <td>
element.
If that element does NOT contain an image I want to play the default sound, but if an image exists in the element play a different sound.
Here is what I have tried, but it doesn’t work, it just plays the default sound.
the result was, it only plays the default sound even though there is an image in some of the other element.
function play_alert_audio() {
var audio_element = document.getElementById("alert_audio");
var tab_element = document.getElementById("record");
for (i = 0; i <= tab_element.childNodes.length - 1; i++) {
// check if the element is an IMG (image type).
if (tab_element.childNodes[i].tagName == 'IMG') {
var audio_element = document.getElementById("alert_audio1");
}
}
if (audio_element.paused) {
audio_element.play();
}
}
<table>
<tr>
<td>Record 1:</td>
<td id='record' onclick='play_alert_audio()'><img src='record.jpg'></td>
</tr>
<tr>
<td>Record 2:</td>
<td id='record' onclick='play_alert_audio()'>Text Only here</td>
</tr>
<tr>
<td>Record 3:</td>
<td id='record' onclick='play_alert_audio()'>Text Only here</td>
</tr>
<tr>
<td>Record 4:</td>
<td id='record' onclick='play_alert_audio()'><img src='record.jpg'></td>
</tr>
</table>
<audio id="alert_audio" src="alert.mp3" type="audio/mpeg" loop="loop"></audio>
<audio id="alert_audio1" src="marimba.wav" type="audio/wav" loop="loop"></audio>
2
Answers
There are some basic programming issues in your code.
tr
element.If you delegate you can just use relative addressing
I changed ID to class and added a tbody with an ID instead