Javascript DOM HTML Source Object create

Introduction

We can create a <source> element via the document.createElement() method:

var x = document.createElement("SOURCE");

Click the button to create two SOURCE elements, and append them to the AUDIO element.

View in separate window

<!DOCTYPE html>
<html>
<body>
<audio controls id="myAudio" autoplay>
Your browser does not support the audio tag.
</audio><br>

<p id="demo"></p>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {//  w  w  w  .  j  a  v  a  2s . co  m
  var x = document.createElement("SOURCE");
  x.setAttribute("src", "sound.mp3");
  x.setAttribute("type", "audio/mpeg");
  document.getElementById("myAudio").appendChild(x);

  var y = document.createElement("SOURCE");
  y.setAttribute("src", "sound.ogg");
  y.setAttribute("type", "audio/ogg");
  document.getElementById("myAudio").appendChild(y);
  document.getElementById("demo").innerHTML = "The audio player now works as it should. Press play to listen to the sound.";
}
</script>

</body>
</html>



PreviousNext

Related