getElementsByClassName not working but getElementById is

拟墨画扇 提交于 2019-11-27 08:49:17

问题


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.


回答1:


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];.



来源:https://stackoverflow.com/questions/15181670/getelementsbyclassname-not-working-but-getelementbyid-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!