by 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 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course