Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu November 21, 2022 . #Element . #HowTo

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.
save
listen
AI Answer
Write Your Answer
loading
back
View All