amillet89
amillet89

Reputation: 75

How to select a div within an iframe?

I'm trying to take the contents of a div within an iframe, delete the iframe, and display only the div. I can't figure out why this won't work- I am not sure of whether to use contentWindow or contentDocument.. Any pointers? Thanks!

I have one div with id "iframe", within that the iframe with id "embedded_article",

<script type="text/javascript">

function getContentFromIframe()

{    
var parent = document.getElementById('iframe');
var child = document.getElementById('embedded_article');

var oldContent = child.contentWindow.document.innerHTML;

var newContent = child.contentWindow.document.getElementById('ec-article').innerHTML;

  document.getElementById('iframe').removeChild(document.getElementById('embedded_article'));


parent.innerHTML = newContent;    

}
</script>

Upvotes: 6

Views: 18567

Answers (2)

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

Your example:

document.getElementById('iframe').removeChild(document.getElementById('embedded_article'));

Should look something like:

var element = frames['iframe'].document.getElementById('embedded_article');

element.parentNode.removeChild(element);

window.frames['yourFrameId'] evaluates to the window object associated with your frame. when you use document.getElementById, you want to use the document belonging to your frame's window, not the document in your main window. The rest should be self-explanitory.

Upvotes: 3

Jaspreet Chahal
Jaspreet Chahal

Reputation: 2750

to get to the div inside an iFrame you can try something like this

     var div = document.getElementById("YourIFrameID").contentWindow.document.body.getElementById("YOUR_DIV_ID")

Upvotes: 2

Related Questions