Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get this child html element in JavaScript?

I have an iframe that looks like this:

<iframe id="iframe2" ...>
    #document
        <html>...</html>
</iframe>

I am trying to get the item underneath the iframe with the html tag.
In JavaScript, when I do:

document.getElementByID("iframe2")

this returns the correct iframe.

However, when I do this:

document.getElementByID("iframe2").childNodes

the return value is [].

document.getElementByID("iframe2").getElementsByTagName("#document") and document.getElementByID("iframe2").getElementsByTagName("html") also return [].

How do I access that html tag?
Also, what is that #document tag called?

like image 883
Di Zou Avatar asked Jun 15 '12 15:06

Di Zou


1 Answers

document.getElementByID("iframe2").contentWindow.document

Or, the variant not supported by older IE,

document.getElementByID("iframe2").contentDocument

This will get you the document object of the embedded page, and from there you can use .documentElement, .body or .head properties to get the html/body/head DOM.

If you want the window object of the embedded page, use contentWindow instead of contentDocument.

MDN has a guide to iframe scripting that you will probably find helpful.

like image 68
apsillers Avatar answered Oct 04 '22 12:10

apsillers