0

The following code works (alert pops up):

var sound = document.getElementById("music");
    sound.addEventListener("play", function () {
    alert("playing");
});
....
....
<audio controls id="music">
    <source src="http://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg"/>
</audio>

But why does this not work?

var sound = document.getElementsByClassName("music");
    sound.addEventListener("play", function () {
    alert("playing");
});
....
....
<audio controls class="music">
    <source src="http://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg"/>
</audio>

This doesn't work either in case getElementsByClassName returns something different than getElementById:

('.sound').addEventListener("play", function () {
    alert("playing");
});
....
....
<audio controls class="music">
    <source src="http://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg"/>
</audio>

All I changed was instead of an ID, I gave it a class (since I have multiple instances of this audio player), and used getElementsByClassName instead of getElementById. I thought getElementsByClassName was compatible with all browsers now? I'm using latest Firefox.

Windbrand
  • 555
  • 4
  • 13
  • 21
  • 1
    `getElementById` returns a single element, `getElementsById` returns a `NodeList` object, i.e. it's basically an array of elements. See the updated answer at your other question. – ultranaut Mar 03 '13 at 02:07
  • that should have been "`getElemensByClassName` returns a `NodeList`". – ultranaut Mar 03 '13 at 02:20
  • Possible duplicate of [What does getElementsByClassName return?](http://stackoverflow.com/questions/10693845/what-does-getelementsbyclassname-return) – Bergi Oct 29 '15 at 10:10

1 Answers1

6

I'm pretty sure document.getElementsByClassName() will return a collection of elements, even if there is only one element with that class name on the page. So you're not actually applying the event listener to the audio element, but an array of elements.

If there will always be only one element of class sound, try var sound = document.getElementsByClassName("music")[0];.

Steven V
  • 16,357
  • 3
  • 63
  • 76
  • Thanks. Though I have multiple instances of this audio player with class name "sound", I guess I will need some kind of for loop to append "eventlistener" to every instance of "sound"? Why doesn't ('.sound').addEventListener("play", function () work though? – Windbrand Mar 03 '13 at 02:31
  • 2
    @Windbrand `('.sound')` is actually just saying get the value of the string ".sound". Which isn't probably what you're trying to do. I think you're trying to use a Javascript framework like [jQuery](http://jquery.com) or [Prototype](http://prototypejs.org/) which use `$` to select elements by classes or IDs like you have. For example, in jQuery you'd write `$('.sound').on('play', function() {alert('playing');});` – Steven V Mar 03 '13 at 02:39
  • @Steven Thank you. your solution helped me a lot. – zahra_oveyedzade Sep 11 '20 at 04:49