I’m using a Learning Management System where users can add YouTube videos, which are then embedded using the iframe tag. They are not embedded responsively automatically. However, I found this JavaScript to wrap the YouTube videos in a div to make them embed responsive:
var embedItem = document.querySelectorAll('iframe[src*="youtube"]');
embedItem.forEach(function(eachEmbed){
let wrapper = document.createElement('div');
wrapper.classList.add('embed-responsive');
wrapper.classList.add('embed-responsive-16by9');
wrapper.appendChild(eachEmbed.cloneNode(true));
eachEmbed.replaceWith(wrapper);
});
This result in a YouTube video being wrapped as follow in HTML:
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/jTwdtMzZMds" allowfullscreen="true" title="YouTube video">
</iframe>
</div>
This works great, but now, I want to wrap this element in another div <div class="video-wrapper rounded">
Basically the output I want for the original iframe tag is:
<div class="video-wrapper rounded">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/jTwdtMzZMds"
allowfullscreen="true" title="YouTube video"></iframe>
</div>
</div>
But I cannot figure out how I can tweak the javascript I found to perform this function automatically. Can anyone adapt the javascript code to perform this function? Does anyone know how to do this?
2
Answers
I’ve assumed that you’re using Bootstrap 4 on your website based on the class names.
As you can see here, you don’t actually need another div. You can apply the new classes to the div created in your existing code to achieve the rounded corners.
Note that I’ve added
overflow-hidden
to the class list. This is necessary to apply the border radius to the inner elements.Then, no need to call
classList.add()
repeatedly. Just put all the classes in a list.I’ve updated variable names here. They weren’t particularly semantic (singular vs. plural), and the repeat made things a bit confusing.
Now, if you actually do need another element for reasons I’m not aware of, you can work in another level of wrapping.
Since you are using Bootstrap, and therefore have the jQuery library available, I’ll offer a simple replacement for all this as an alternative.