简体   繁体   English

如何定位没有ID或Class属性的iframe中的元素?

[英]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. 由于某些技术问题,我无法将任何id或类添加到我工作的iframe中,并且该iframe有时不显示任何内容,而是使用空白空间。 I wanted to make the iframe disappear when it loads blank, to protect my page's structure with javascript. 我想让iframe在加载空白后消失,以使用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> . <iframe>之前删除外部的<div> <iframe>

Add id="ifr" to <iframe> tag. id="ifr"添加到<iframe>标记。

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

EDIT : Alternatively you can use iframe index in your document. 编辑 :或者,您可以在文档中使用iframe索引。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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