How to use JavaScript to dynamically change a video’s source?

Sometimes, we want to use JavaScript to dynamically change a video’s source.

In this article, we’ll look at how to use JavaScript to dynamically change a video’s source.

How to use JavaScript to dynamically change a video’s source?

To use JavaScript to dynamically change a video’s source, we can set the src property of the source element to the URL of the video.

For instance, we write:

<video controls>
  <source src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_640_3MG.mp4">
</video>

to add the video element with the source element’s src attribute set to a video path.

Then we write:

const source = document.querySelector("video > source")
source.src = "https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4"

to select the source element in the video element with document.querySelector.

Then we set the src property to the video URL string.

Conclusion

To use JavaScript to dynamically change a video’s source, we can set the src property of the source element to the URL of the video.