Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to use JavaScript to dynamically change a video’s source?”

Thank you! I’ve been trying to set the src of a videojs video and this is the only syntax I found that would work.

Leave a Reply

Your email address will not be published. Required fields are marked *