Sometimes, we want to change audio element src with JavaScript.
In this article, we’ll look at how to change audio element src with JavaScript.
How to change audio element src with JavaScript?
To change audio element src with JavaScript, we set the element’s src
attribute.
For instance, we write
const audio = document.getElementById("audio");
const source = document.getElementById("audioSource");
source.src = elm.getAttribute("data-value");
audio.load();
audio.play();
to select the audio element with getElementById
.
Then we get the element with the data-value
attribute with getElementById
.
We use the data-value
attribute value for the src
attribute’s value.
Next we call load
to preload the audio element with the clip from the new URL.
Then we call play
to play it.
Conclusion
To change audio element src with JavaScript, we set the element’s src
attribute.