Sometimes, we want to add sources to HTML5 video in JavaScript.
In this article, we’ll look at how to add sources to HTML5 video in JavaScript.
How to add sources to HTML5 video in JavaScript?
To add sources to HTML5 video in JavaScript, we can create a new source element with createElement
.
For instance we write:
const source = document.createElement('source');
source.src = 'http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv';
source.type = 'video/ogg';
const video = document.createElement('video');
video.controls = true
video.appendChild(source);
document.body.appendChild(video);
We call createElement
with 'source'
to create a source element.
Then we set the src
and type
attributes of it by setting their respective properties.
Next, we call createElement
again to create a video element.
And we set the controls
property to true
to set the controls
attribute to true
.
Then we append the source
element as the child of video
with appendChild
.
And then we append the video element as the child of body with document.body.appendChild
.
Conclusion
To add sources to HTML5 video in JavaScript, we can create a new source element with createElement
.