As you can see, I have two different audio files that correspond to id="6.1". Is there a way to use getElementById that calls just the "straight" class of the Id's content? I know you can call options within in Id. I tried "document.getElementById('6.1').options[0].text.play()", but that didn't work. (Obviously, I'm new at this.) Anyone have a hint?
<audio id="6.1" preload='none'>
<source class="straight" src='audio/6.1.mp3' type='audio/mpeg' />
<source class="swing" src='audio/swing/6.1.mp3' type='audio/mpeg' />
</audio>
<button onclick="document.getElementById('6.1').play()">▶</button>
The .
notation is used to denote class selector and it should not be used in the id. So, selector #6.1
will select the element having id as 6 and class 1.
Use querySelector with attribute=value selector.
document.querySelector('[id="6.1"] .straight').classList.add('green');
Demo
document.querySelector('[id="6.1"] .straight').classList.add('green');
.green {
color: green;
font-weight: bold;
}
<div id="6.1"> <span class="straight">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, unde.</span>
<span class="swing">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
</div>
You can use jquery:
$("#6\\.1 .straight")[0]
Or if you insist on plain JavaScript DOM:
document.getElementById("6.1").getElementsByClassName("straight");
However, I don't think this will actually do what you wanted to do. The multiple <source>
s are supposed to be fallback audio sources, all containing the same audio just in different formats (e.g. MP3, Ogg). HTML specifies an algorithm that the browser use to negotiate which alternative to use, based on what the browser is capable of playing. You shouldn't need any JavaScript to do the automatic negotiation, the browser should automatically select which alternative to play.
What are you actually trying to do?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With