Yes, it is possible to create everything using JavaScript without the need for any pre-existing elements in the HTML body.
Here is a straightforward way to create a video element using JavaScript:
var videlem = document.createElement("video");
/// ... set up parameters like poster image, size, position, etc.
/// now, add video sources:
var sourceMP4 = document.createElement("source");
sourceMP4.type = "video/mp4";
sourceMP4.src = "path-to-video-file.mp4";
videlem.appendChild(sourceMP4);
//// repeat the process for ogg/ogv and webm sources
Before proceeding with this, it's important to check if the browser supports the video element and which file formats can be played. This can be done as follows:
var supportsVideoElement = !!document.createElement('video').canPlayType;
If the video element is supported, you can test which video formats are compatible:
var temp = document.createElement('video');
var canPlay_MP4 = temp.canPlayType('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
var canPlay_OGV = temp.canPlayType('video/ogg; codecs="theora,vorbis"');
var canPlay_WEBM = temp.canPlayType('video/webm; codecs="vp8,vorbis"');
After ensuring compatibility, you can dynamically add the video element to your page using only JavaScript with the appropriate video sources set. In case of issues related to server-side configurations, adding certain directives to .htaccess might resolve the problem:
AddType video/ogg .ogv
AddType video/ogg .ogg
AddType video/mp4 .mp4
AddType video/webm .webm
This step may or may not be necessary depending on server settings. If playback issues persist from the server but not locally (e.g., localhost), including the above lines in .htaccess within the same folder as the video files could address the problem.
To make the video element accessible via getElementById(...), simply assign an ID during creation:
var videlem = document.createElement("video");
videlem.id = "xxxxxx";
Later on, you can easily locate the element using:
var videlem = document.getElementById("xxxxxx");
While setting an ID can facilitate access, it may not be required if the element has already been created and referenced by a variable - in such cases, direct usage is preferred.
I trust this information proves helpful :-)