iframeの高さ調整

Quick Edit Pencil

【Javascript】iframeの内容を取得したい at softelメモ

問題

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>

このブログの人気の投稿

PowerShellのGetDetailsOf メソッドでプロパティの詳細情報のID番号と項目名を列挙します

Blender: 辺の長さを数値で指定するアドオン

書字方向 横書方向変換スクリプト 左書きから右書きへ(コピペ用途)

ヤバい!JAPANNEXT WQHD対応 27型ワイド液晶ディスプレイ「JN-IPS2716WQHD」を注文してみた!!!

決定版 Edgeでローカルファイルを開く パワーシェルスクリプト (ウインドウズでドロップレット)

PowerShellで複数ファイルのプロパティを取得する方法(準備編)

カルチャーラジオ 科学と人間 薬と毒の歴史をひも解く 日本薬科大学教授…船山信次

Windows10でアプリケーションごとに輝度を設定、自動で変更する - AutoHotkey