Author -  Sai gowtham

How to get element from an Iframe in JavaScript

In this tutorial, we are going to learn about how to get the html elements from an Iframe in JavaScript.

Consider we have a following <iframe> element in our index.html file.

<iframe id="myIframe" src="/index.html" width="500px" height="500px"></iframe>

Getting the element in Iframe

To get the element in an iframe, first we need access the <iframe> element inside the JavaScript using the document.getElementById() method by passing iframe id as an argument.

const iframe = document.getElementById("myIframe");

Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.

const iWindow = iframe.contentWindow;
const iDocument = iWindow.document;

// accessing the element
const element = iDocument.getElementsByTagName("p")[0];
element.style.color = "green";

In the example above, we have accessed the first <p> element from an Iframe and changed its color to green.

Similarly, we can access and modify other elements in the iframe using document object.

Note: If you want to access an iframe, it should be on the same domain otherewise you can’t access it because of security reasons (like XSS).

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY