Make Responsive YouTube / Vimeo videos using JavaScript

I came across a client website that already has ton of embed YouTube videos. The client requirement was make them responsive.

My plan was to add a wrapper around the iframe using javascript and required styling.

You can find following css snippet on many sites. including . follow the link for in depth description of css styling.

CSS Styles

	.video-container {
		position: relative;
		padding-bottom: 56.25%;

	.video-container iframe {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;

After adding the styling when we wrap youtube or vimeo embed code inside a div with class ‘video-responsive. It will be responsive. but for a already existing website It’s tedious to edit each post and add wrappers.

Let’s check how we can do that using Javascript.


document.addEventListener("DOMContentLoaded", function (event) {
  document.querySelectorAll("iframe").forEach((iframe) => {
    if (iframe.src.indexOf("youtube") || iframe.src.indexOf("vimeo")) {
      const videoWrapper = document.createElement("div");
      videoWrapper.className = "video-container";

      iframe.parentNode.insertBefore(videoWrapper, iframe);

Here we are running the script after content is loaded. we are getting every iframe on the page using querySelectorAll

It gives us an element array. we repeat it and check src of each element that src includes the string “youtube” or “vimeo” ( so this works for both ) using indexOf

Then we create a div element. add ‘video-container’ class. and add matched iframe into the created div element.