Create Audio element dynamically in Javascript

前端 未结 1 1155
难免孤独
难免孤独 2021-02-13 09:02

I need to create an audio tag dynamically in between

Need to create:

1条回答
  •  抹茶落季
    2021-02-13 09:52

    You can do it in multiple ways. Here are some:

    Using innerHTML

    Use this if you want to replace all of the inner HTML, and do not care about references to elements.

    document.getElementById('song').innerHTML = '

    Using appendChild

    Use this if you want to have a reference to your audio element, and maybe other elements that are already in there.

    var sound      = document.createElement('audio');
    sound.id       = 'audio-player';
    sound.controls = 'controls';
    sound.src      = 'media/Blue Browne.mp3';
    sound.type     = 'audio/mpeg';
    document.getElementById('song').appendChild(sound);
    

    Using insertAdjacentHTML

    Use this method if you have other elements in there that you previously referenced and want to keep a reference to, but don't care about a reference to the audio element for now.

    document.getElementById('song').insertAdjacentHTML('beforeend', '

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