简体   繁体   中英

How to target an element inside an iframe that has no Id or Class attributes?

I can't put any id or class to the iframe I work because of some technical issues, and this iframe sometimes don't show any content inside and I am having a blank space instead. I wanted to make the iframe disappear when it loads blank, to protect my page's structure with javascript.

Here is the code I wanted to make it disappear when there are no contents.

<div id="myDiv">

 <iframe width="363" height="300"  src="javascript:false">

    <div id="iframeDiv"> 
     ----Contents----
    </div>

  </iframe>

 </div>

I tried below script but somehow it doesn't work. Thanks in advance.

<script type="text/javascript">
 setTimeout(function () {

  var  myTag=document.getElementById('myDiv').getElementsByTagName('iframe');
  var myTagContent = myTag.contentDocument || iframe.contentWindow.document;
  var myTagDiv = myTagContent.innerDoc.getElementById('iframeDiv');
  if (myTagDiv === null) 
     {
     document.getElementById("myDiv").style.display = "none";
     }
 }, 500);
 </script>

Remove the outer <div> before <iframe> .

Add id="ifr" to <iframe> tag.

Then: iframeDivElement = window.parent.getElementById('ifr').document.getElementById(iframeDiv');

EDIT : Alternatively you can use iframe index in your document.

iframeDivElement = window.parent.frames[0].document.getElementById(iframeDiv');

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