getElementsByClassName not working but getElementById is

前端 未结 1 1686
一生所求
一生所求 2020-12-12 05:32

The following code works (alert pops up):

var sound = document.getElementById(\"music\");
    sound.addEventListener(\"play\", function () {
    alert(\"play         


        
相关标签:
1条回答
  • 2020-12-12 06:06

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

    0 讨论(0)
提交回复
热议问题