views:

31

answers:

1

I've got an iframe that I filled like this:

var usableUrl = unescape(url);
var iframe = $("<iframe id='pageContentDownloader' name='pageContentDownloader' style='display:block'></iframe>");
$("body").append(iframe);
iframe.load(usableUrl, null, ondocloaded);
iframe.css({ "width": $(window).width(), "height": $(window).height(), "border": "0px" });

Later on, I want to in-place replace all of the <p>s and <div>s with modified versions of themselves:

$("#pageContentDownloader").contents().find("p, div")
            .each(function () {
                var para = $(this).text();
                var words = para.split(" ");
                var aWords = new Array();
                $.makeArray(words, aWords);
                var newPara = makePara(aWords);
                $(this).replaceWith(newPara);
            });

But for some reason, the last command doesn't work. I can see that $(this) is the original para inside the iframe (I can see its content and I know that it is the original unmodified version of the para), and newPara definitely contains the appropriately modified content.

The $(this).replaceWith() seems not to be working properly. The comments about issues with replacing tags with text elements in the replaceWith API docs don't apply here, since the replacement is a <div> filled with <span>s.

Is this some weird <iframe>/Query 1.4+ issue? I've tested this on HTML5, XHTML with IE8 and Chrome 5 beta. All of them leave me an empty iframe.

+2  A: 

You're not showing what newPara() does but if it creates a new DOM element, that could be the root of the problem: You're implicitly moving a node from one document to another. It could be that the iframe doesn't take kindly to that (although in principle, there should be an error message then.)

If that is true, you would have to create the DOM element in the iframe, or insert raw HTML instead of a finished node.

You could try using $(iframe).document.createElement("p"); instead to create the element

$(html) has a second argument, ownerDocument. Try explicitly specifying $(iframe).document as the ownerDocument when creating the element to be replaced.

Pekka
newPara creates a new div node ( like this $("<div/>") ) and then appends various spans to that node before replacing the original node with the new one. Why should the context in which the Node was create make any difference to the replaceWith command? An object is an object at that point, right?
Andrew Matthews
@ANdrew cross-document operations on nodes are notoriously unstable. See e.g. http://stackoverflow.com/questions/2284356/cant-appendchild-to-a-node-created-from-another-frame I added something to try out to my answer.
Pekka
Hi @pekka, thanks! I'll give it a try, and get back to you.
Andrew Matthews
@Andrew all right. If it doesn't help, I think you should add the code of `newPara()` to your question for completeness' sake!
Pekka