Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Audio element dynamically in Javascript

I need to create an audio tag dynamically in between <div class="audio-player" id="song"></div>

Need to create:

<audio id="audio-player" controls="controls" src="media/Blue Browne.mp3" type="audio/mpeg">

in: <div class="audio-player" id="song"></div> please help its very important for me

like image 377
Samuel Scott Avatar asked Jun 09 '16 20:06

Samuel Scott


People also ask

What is new audio in JavaScript?

Audio() The Audio() constructor creates and returns a new HTMLAudioElement which can be either attached to a document for the user to interact with and/or listen to, or can be used offscreen to manage and play audio.


1 Answers

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 = '<audio id="audio-player" controls="controls" src="media/Blue Browne.mp3" type="audio/mpeg">';

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', '<audio id="audio-player" controls="controls" src="media/Blue Browne.mp3" type="audio/mpeg">');
like image 125
blex Avatar answered Sep 20 '22 19:09

blex