获取文本javascript + iframe

时间:2013-12-15 07:24:55

标签: javascript html iframe

我有HTML代码

网站index.html

<html>
<body>
  <iframe id="html2" frameborder="0" src="html2.htm" marginwidth="0" marginheight="0" style="height: 492px;"></iframe>
</body>
</html> 

网站html2.htm

<html>
<body>
  <div><p id='123'>hello</p></div>
</body>
</html>

当我在网站index.html document.getElementById('123')中使用return = null;时 我怎么能得到它

1 个答案:

答案 0 :(得分:0)

您需要先通过以下方式访问iframe的innerDoc:

var iframe = document.getElementById('html2');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

获得对象后,现在可以访问:

innerDoc.getElementById('divId');

对于html中的ID,您需要遵循以下规则:

ID应匹配:

[A-Za-z][-A-Za-z0-9_:.]*
  1. 必须以A-Z或a-z字符开头
  2. 可能包含_(连字符),:(可乐)和。(点)
  3. 但是应该避免:.因为jQuery选择器与类和过滤器发生冲突。