Graham T
Graham T

Reputation: 966

reading an iframe's DOM

Similar to Firebug Inspect I have a block of code to read the DOM and upon mouseover highlight the current element, and upon click to print out that current element's DOM location. See demo: http://jsfiddle.net/94EaH/4/

I'm trying to modify the code to work on the content within an iframe. I don't want it to work on the current page AND iframe's DOM, because I know that won't work. I want to change the selector the code is bound to, to be the iframe. The iframe is of course embedded within a page, but only the iframe's DOM is being analyzed.

I can manipulate the parent through the iframe like this:

<iframe id="testFrame" src="blah.html" width="200px" height="200px"></iframe>
<div id="testBox">text text text</div>

$("#testFrame").contents().bind("click", function() {
   $('#testBox').css('color', 'green');
});

But if I add one more line to modify the content of a DIV inside the iframe.. nothing.

$("#testFrame").contents().bind("click", function() {
   $('#testBox').css('color', 'green');
   $('#iframeDiv').css('color', 'red'); //this produces no result
   console.log(event.target); // I get no information out of this also..
});

http://jsfiddle.net/94EaH/3/

It's difficult to show full functionality, since blah.html (iframe source) can't be displayed on jsfiddle..

Any ideas on how I could extend this functionality to an iframe's DOM instead of the #container element of the current page I've used in the example?

Upvotes: 1

Views: 104

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18322

If you're trying to access an element in an Iframe with jQuery from the parent window, then you've got a problem. Imagine you've got a iframe. Inside the iframe, there's a div with id 'container'. If you do this from the parent document, $('#container'), you'll find the jQuery object is empty.

jQuery is bound to the window and document objects of the page in which it is declared (loaded). It does no matter that you're constructing it from an event handler bound to the iframe, the $ function you're using still belongs to the parent window. If you load jQuery in the iframe's page, however, you could get references to the objects like this:

$('#testFrame')[0].contentWindow.$('#container');

Here, the first '$' and the second '$' do not refer to the same jQuery constructor.

Edited I forgot the [0] to access the first iframe in the jQuery object.

I hope this helps you.

Upvotes: 1

Related Questions