简体   繁体   中英

How to access iframe inside and iframe using pure javascript

I have the below code that is in my DOM and I want to get height of the #iframe2

Basically, I have to change the height of #iframe1 whenever the height of #iframe2 changes. I have added a link to screenshot below for what I am exactly trying to achieve.

http://i.imgur.com/y3lz3v4.png

<div id="gpt-leaderboard">
   <iframe id="iframe1">
         <iframe id="iframe2" >
           <!-- Banner with dynamic height loads here-->
         </iframe>
    </iframe>
 </div>

I am using the below code to get the height but it is not working

document.getElementById("gpt-leaderboard").getElementsByTagName('iframe')[0].getElementsByTagName('iframe')[0].style.height;

Any ideas why?

What you are trying to do will not work assuming your implementation is that your two iframes are nested in the main page.

when iframe1 is loaded, it will be defaulted to a blank document. This will mean iframe2 is removed, as anything inside the <iframe> tag will be replaced.

To just get your HTML correct, you will have to have your first iframe 's src attribute set to a page containing iframe2

Edit: You can see an example of one approach using jquery here: http://jsfiddle.net/D9BX8/ (note: i have used jquery instead of "raw JS" since it's what i know. I'm sure with some googling you can translate it down to basic JS if you don't use jquery on your site)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM