こんにちは、さち です。
先日、「JavaScript」を使って <iframe> の中にある要素を取得しようとしたのですが、いつもの普通の方法では上手くいきませんでした。
少し特殊なコードの記述が必要だったので、備忘録としてこの記事を残しておきます。
失敗した方法
コード
HTML
<body>
<iframe id="ifr" src="child.html"></iframe>
</body>
<iframe> の中身「child.html」は下記のとおり。
<body> <p>iframe の中だよ</p> </body>
JavaScript
const ifr = document.getElementById('ifr');
let elm = ifr.querySelector('p');
console.log(elm.textContent);
結果
コンソール
Uncaught TypeError: can't access property "textContent", elm is undefined
「変数 elm が定義されていない」とエラーが出てしいました。
原因は、ifr.querySelector('p') で要素を取得できていないこと。いつもの記述方法だと <iframe> 内の要素は取得できないわけです。
解決方法
コード
HTML
<body> <iframe id="ifr" src="child.html"></iframe> </body>
<body> <p>iframe の中だよ</p> </body>
JavaScript
const ifr = document.getElementById('ifr');
const doc = ifr.contentDocument;
let elm = doc.querySelector('p');
console.log(elm.textContent);
ifr.contentDocument を追加・経由することで、要素の取得ができるようになります。
追加したコードの効果をざっくり説明します。要素を取得するときに document.getElementsBy... のように先頭に document を付けますよね? これを <iframe> でもできるようにするために <iframe> 内の document を取得しています。
結果
コンソール
iframe の中だよ
<iframe> 内の要素を取得できました。
<iframe> 内の window を取得したいときは ifr.contentWindow のように書きますdocument が window.document と同じ意味であるように、ifr.contentDocument を ifr.contentWindow.document と書くこともできます


コメント