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).