How ToJavaScriptMake Web StoriesQuiz GeneratorFAQ Schema GeneratorTable Maker3schools TranslateMore Tools..
Apu
Apu 11/21/2022

How to Get Element from an Iframe in JavaScript

In this article we will learn how we can access an element (p, div, h1 etc.) from an iframe using JavaScript.

We have the following iframe with an id my-iframe.

<iframe id="my-iframe" src="https://www.3schools.in/p/example.html" width="300" height="200"></iframe>

To get an element from iframe, first we have to access the iframe using the JavaScript querySelector() method. E.g.

const myIframe = document.querySelector('#my-iframe');

Now, the variable myIframe has a property contentWindow which has the body object.

By using the body object, we can access all elements from iframe.

 const iWindow = myIframe.contentWindow;
 const iDocument = iWindow.document.
 
 const iElement = iDocument.querySelector("#note");
 iElement.style = "background-color:red";

Whenever you try to access an element from an iframe you may get some errors. There can be two reasons for the error.

  1. You are trying to get an element from the iframe before the iframe is fully loaded.
  2. The iframe should be in the same domain otherwise you cannot access an element from the iframe for security reasons.
Share

How to Get Element from an Iframe in JavaScript

0
In this article we will learn how we can access an element (p, div, h1 etc.) from an ifra…
asked
0 answers

Write an Answer

Related Posts
Write an answer
back