fngryboi
fngryboi

Reputation: 64

Apply a parent to an iframe

I have fixed the video's height and width ratio using FluidVids.js. Now I want to wrap my iframe with a parent. I know that the parents working by manually throwing it inside the HTML-file. But the template I am working on needs to do this automatically.

So what I'm asking for is a (pure) JavaScript for wrapping my iframe with a div class I call fwparent. The HTML looks something like this:

<div class="post">
...
<iframe src="a-nice-video" allowFullscreen></iframe>
...
</div>

FluidVids overrides the standard sizes on the iframe. But my div class post has some paddings that I need to override with the fwparent class!

So the result should be something like this:

<div class="post">
...
<div class="fwparent"><iframe src="a-nice-video" allowFullscreen></iframe></div>
...
</div>

And remember, pure JavaScript. No extra HTTP requests for jQuery or stuff like that...

I have no experience what-so-ever with JavaScript. So be nice ;)

I have something similar which applies to images:

function imgWrap(parent) {
if (!parent || parent.nodeType !== 1) {
    return false;
}
else {
    var images = parent.getElementsByTagName('img'),
        newDiv = document.createElement('div'),
        tmp;
    newDiv.className = 'parent';
    for (var i = 0, len = images.length; i < len; i++) {
        tmp = newDiv.cloneNode(true);
        parent.insertBefore(tmp, images[i])
        tmp.appendChild(images[i]);
    }
}
}

imgWrap(document.querySelector('div.post'));

And jQuery does something like this:

$('iframe').wrap('<div class="fwparent" />');

But I want it to be pure JavaScript. And apply to all iframes...

Upvotes: 1

Views: 1720

Answers (1)

Teemu
Teemu

Reputation: 23416

Something like this?

var div = document.getElementById('wrapper').appendChild(document.createElement('div'));
div.className = 'fwparent';
div.appendChild(document.getElementById('iframe'));

EDIT

To wrap more than one iframe you need to use a loop:

var frms = document.getElementsByTagName('iframe'),
    post = document.getElementById('post'),
    div, n;
for (n = 0; n < frms.length; n++) {
    div = post.appendChild(document.createElement('div'));
    div.className = 'fwparent';
    div.appendChild(frms[0]); // *
}

* = looks like we need 0 instead of n here, a live nodelist created by getElementsByTagName() is updated when appending iframes to a new location.

A live demo at jsFiddle.

Upvotes: 2

Related Questions