Lalchand
Lalchand

Reputation: 7827

append element in head of an iframe using jquery

i want to append a style sheet(css) link to the head of an iframe using jquery . i tried with the following code but not working.

$('#tabsFrame').contents().find("head").append(cssLink);

Upvotes: 9

Views: 18046

Answers (4)

mateuscb
mateuscb

Reputation: 10710

This could be related to IE not allowing you to add elements in the DOM, check out the clever solution here

EDIT:

Thanks @kris, good advice to add more info in case links break:

Here is the main code snippet from the link, in case it goes out again. (This is only needed with some IE version, for the most part, the other answer work just fine)

var ifrm;

//attempts to retrieve the IFrame document    
function addElementToFrame(newStyle) {
    if (typeof ifrm == "undefined") {
        ifrm = document.getElementById('previewFrame');
        if (ifrm.contentWindow) {
            ifrm = ifrm.contentWindow;
        } else {
            if (ifrm.contentDocument.document) {
                ifrm = ifrm.contentDocument.document;
            } else {
                ifrm = ifrm.contentDocument;
            }
        }
    }

    //Now that we have the document, look for an existing style tag
    var tag = ifrm.document.getElementById("tempTag");

    //if you need to replace the existing tag, we first need to remove it
    if (typeof tag != "undefined" || tag != null) {
        $("#tempTag", ifrm.document).remove();
    }

    //add a new style tag
    $("HEAD", ifrm.document).append("");
}

Upvotes: -1

animacom
animacom

Reputation: 31

well, you can check with this:

$('#tabsFrame').contents().find("head")[0].appendChild(cssLink);

Upvotes: 3

the JinX
the JinX

Reputation: 1980

I believe you can't manipulate the content of an iframe because of security. Having you be able to do such a thing would make cross-site-scripting too easy.

The iframe is totally seperate from the DOM of your page.

Also, java and javascript are two completely different things!

Follow the Link to see the difference here

Upvotes: 0

DKSan
DKSan

Reputation: 4197

i am used to append data to an iframe by using this line of code

$('body', window.frames[target].document).append(data);

In your case, this line would look like this

$('head', window.frames['tabsFrame'].document).append(cssLink);

EDIT:

Add <head></head> to the iframe and change your var cssLink to

cssLink = '<link href="cupertino_1.4/css/cupertino/jquery-ui-1.8.7.custom.css" type="text/css" rel="Stylesheet" class="ui-theme" />

Upvotes: 6

Related Questions