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番号と項目名を列挙します

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

簡単 YouTube動画をダウンロード、音声のみ保存する方法 2019

DOMノードオブジェクトを文字列に変換する

PowerShellでJPG画像のリサイズとウォーターマーク画像との合成を同時に行う

AppleScript 改行 コード 置換

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