获取文本javascript+iframe

get text javascript + iframe

本文关键字:javascript+iframe 取文本 获取      更新时间:2023-09-26

我有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;如何获得

您需要首先通过以下方式访问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. 可能包含_(连字符)、:(colan)和。(点)

但是应该避免CCD_ 3和CCD_。