JSFiddle - React, Tailwind, and code Playground
HTML
<div class="js-video-container"></div>
<template class="js-video-template">
<iframe class="js-video elementor-background-video-embed" frameborder="0" allowfullscreen="1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" title="YouTube video player" width="640" height="360"></iframe>
</template>
JavaScript
// Interface w/ HTML
const SELECTORS = Object.freeze({
VIDEO_CONTAINER: '.js-video-container',
VIDEO_TEMPLATE: '.js-video-template',
VIDEO: '.js-video',
})
const VIDEO_DATA_LIST = [
{ src: 'https://www.youtube.com/embed/qoXa-tTkitg' },
{ src: 'https://www.youtube.com/embed/iphcyNWFD10' },
{ src: 'https://www.youtube.com/embed/IvUU8joBb1Q' },
{ src: 'https://www.youtube.com/embed/zGxwbhkDjZM' },
]
// (Just shortened this using arrow functions)
const getRandomArrayItem = array =>
array[Math.floor(Math.random() * array.length)]
const insertRandomVideo = (templateElement, parentElement, videoSelector, videoDataList) => {
const { src } = getRandomArrayItem(videoDataList)
// Create a videoElement from the template
const videoElement = templateElement.content.cloneNode(true).querySelector(videoSelector)
videoElement.src = src
// (Can also set other values if you include them in the data list)
parentElement.appendChild(videoElement)
}
// Run the function
insertRandomVideo(
document.querySelector(SELECTORS.VIDEO_TEMPLATE),
document.querySelector(SELECTORS.VIDEO_CONTAINER),
SELECTORS.VIDEO,
VIDEO_DATA_LIST,
)