Writing and Updating DOM Elements in a Frame

Handling writing and updating objects in an iframe can be bothersome in most browsers. Sure things like jQuery tend to help, but not always.

A normal way to access a frame in jQuery is below:


$("#FRAME").contents()


Now, lets say you actually want to get another element inside of the frame, lets get the HEAD element.


$("#FRAME").contents().find("HEAD");



Awesome, we now have the head element of the document in the frame. Lets add a style tag to it.


$("#FRAME").contents().find("HEAD").append('

');


Now this worked in most browsers… I say most for a reason. This was an actual use case I was trying to accomplish. However, good ole’ IE wouldn’t let me actually add a DOM element
anywhere in the frame. The only thing I was able to do was to add in style tags on the elements. So how did I get around it?


var ifrm;

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, lets add a new style tag
*/
$("HEAD", ifrm.document).append("

");

}


Wow, interesting mix of using straight JavaScript and jQuery in there. However, what happens when I want to just update the same style tag with something new?


var ifrm;

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");

/*
* Hmm, this doesn't look right, but it is. IE will not allow you
* to use a pre-existing style tag and set the innerHTML for that
* element. Which means, we can't create the style tag in another
* function and pass back the element and then set the innerHTML
* to what we need. Plus, with this limitation, now we need to
* actually remove the style element from the DOM and recreate
* it each time. LAME.
*/
if (typeof tag != "undefined" || tag != null){
$("#tempTag", ifrm.document).remove();
}

/*
* We only have one shot at writing out the style tag, we must
* include the css at that point as well or IE will bail with an
* unsuported method exception.
*
* add a new style tag
*/
$("HEAD", ifrm.document).append("

");
}


And that is how you can add new elements to a DOM in an iframe inside of your page.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>