Skip to main content

How to Create a Video Element in JavaScript

Dynamically creating and adding <video> elements to a page is a common requirement for building custom video players, interactive galleries, or ad platforms. This involves more than just creating the element; it requires setting its attributes correctly and, most importantly, ensuring cross-browser compatibility by handling different video formats.

This guide will teach you the modern, standard method for creating a <video> element. You will learn how to build a single, reusable function that can intelligently select a supported video source and configure the player with common attributes like controls and poster.

The Core Process: Create, Configure, and Append

The process of creating a new video element involves three main steps:

  1. Create: Use document.createElement('video') to create a new, detached <video> element.
  2. Configure: Set its properties and attributes, such as src, controls, width, height, and poster.
  3. Append: Add the newly created element to the DOM tree using a method like appendChild(), making it visible on the page.

The Modern Solution: A Reusable createVideo Function (Best Practice)

The most professional and reusable approach is to encapsulate the creation and configuration logic in a single function. This function should also handle the crucial task of selecting a video format that the user's browser can actually play.

The Reusable Function:

/**
* Creates a video element with appropriate sources and attributes.
* @param {Array<{src: string, type: string}>} sources An array of video sources.
* @param {object} [options] Optional configuration for video attributes.
* @returns {HTMLVideoElement|HTMLParagraphElement} The video element or a fallback paragraph.
*/
function createVideo(sources, options = {}) {
const video = document.createElement('video');

// Set standard attributes from the options object
video.controls = options.controls ?? true;
video.autoplay = options.autoplay ?? false;
video.muted = options.muted ?? false;
if (options.width) video.width = options.width;
if (options.height) video.height = options.height;
if (options.poster) video.poster = options.poster;

// Find the first source that the browser can likely play
const supportedSource = sources.find(source =>
video.canPlayType(source.type)
);

if (supportedSource) {
video.src = supportedSource.src;
} else {
// If no video format is supported, return a fallback element
const fallback = document.createElement('p');
fallback.textContent = 'Sorry, your browser does not support the available video formats.';
return fallback;
}

return video;
}

How the Reusable Function works:

  • document.createElement('video'): This creates the <video> element in memory.
  • Setting Attributes: We use direct property assignment (e.g., video.controls = true) to set common attributes. The nullish coalescing operator (??) provides sensible defaults.
  • video.canPlayType(source.type): This is the most critical part for cross-browser compatibility. Before we set the src, we check if the browser can play the video format (e.g., 'video/mp4'). The method returns:
    • 'probably': The browser is confident it can play the format.
    • 'maybe': The browser thinks it might be able to play the format.
    • '' (empty string): The browser cannot play the format.
  • .find(): We use the find() method on the sources array to get the first source that the browser reports it can play.
  • Fallback: If no supported source is found, we gracefully return a <p> element with an error message instead of a broken video player.

Practical Example: Adding a Video Player to the Page

With our createVideo utility function, creating and adding a new video player to the page becomes incredibly simple and readable.

<div id="video-container"></div>

Solution:

// 1. Define the video sources, from most preferred to least preferred format
const videoSources = [
{ src: 'path/to/my-video.mp4', type: 'video/mp4' },
{ src: 'path/to/my-video.webm', type: 'video/webm' },
{ src: 'path/to/my-video.ogv', type: 'video/ogg' },
];

// 2. Define the options for the video player
const videoOptions = {
width: 320,
height: 240,
poster: 'path/to/my-image.jpg',
};

// 3. Create the video element using our reusable function
const myVideo = createVideo(videoSources, videoOptions);

// 4. Append the new element to the container
const container = document.getElementById('video-container');
container.appendChild(myVideo);

Conclusion

Dynamically creating video elements is a powerful feature for modern web applications.

  • The core process is to create (createElement), configure (set properties like src and controls), and append (appendChild).
  • The most important step for robust applications is to check for browser compatibility using video.canPlayType() and provide multiple video formats.
  • Encapsulating this logic in a reusable function is a best practice that makes your code cleaner, more maintainable, and less error-prone.