Di Zou
Di Zou

Reputation: 4619

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?

Upvotes: 5

Views: 11239

Answers (4)

Bunlong
Bunlong

Reputation: 662

Please try this code:

var a = document.getElementById("iframe2").firstChild;

Upvotes: 2

Alexandre Khoury
Alexandre Khoury

Reputation: 4032

Try this :

var a = document.getElementById("iframe2").getElementsByTagName("*")[0];

Upvotes: 2

Matt Coughlin
Matt Coughlin

Reputation: 18906

Does the URL for the IFrame content have the same domain as the parent page? If not, you won't be able to access anything inside the IFrame due to the same-origin policy.

Upvotes: 0

apsillers
apsillers

Reputation: 116030

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.

Upvotes: 6

Related Questions