【Javascript】iframeの内容を取得したい
問題
iframeの内容を取得したいのだが、なぜか取得できない。
<script>
//iframe要素を作る
$('body').append('<iframe id="example1" src="http:/\/www.softel.co.jp/"></iframe>');
//iframeのdocumentを取得する
var doc = $('#example1').get(0).contentDocument;
//例えばa要素の数 → あるはずのページでも0と返ってくる
alert(doc.getElementsByTagName('a').length);
</script>
答え
あせってiframeの読み込みを待たずにdocumentを取得しようとすると何も取れない。
以下のように loadを待つ(jQueryを読み込んでいる前提で書いています)
<script>
$(function(){
//iframe要素を作る
$('body').append('<iframe id="example1" src="http:/\/www.softel.co.jp/"></iframe>');
//iframeのload時にdocumentを取得するようにする
$('#example1').on('load', function(){
//iframeのdocumentを取得する(Mozilla系 || 古いIE系)
var doc = this.contentDocument || this.contentWindow.document;
//例えば最初のimg要素のalt属性を取得する
alert(doc.getElementsByTagName('img')[0].getAttribute('alt'));
});
});
</script>