Create a Source Element - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Source

Introduction

You can create a <source> element by using the document.createElement() method:

Demo Code

ResultView the demo 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()">create two SOURCE elements, and append them to the AUDIO element</button>

<script>
function myFunction() {/*  w w  w.ja va  2s .c  om*/
    var x = document.createElement("SOURCE");
    x.setAttribute("src", "your.mp3");
    x.setAttribute("type", "audio/mpeg");
    document.getElementById("myAudio").appendChild(x);

    var y = document.createElement("SOURCE");
    y.setAttribute("src", "your.ogg");
    y.setAttribute("type", "audio/ogg");
    document.getElementById("myAudio").appendChild(y);
    document.getElementById("demo").innerHTML = "The audio element created. Press play to listen.";
}
</script>

</body>
</html>

Related Tutorials