Consider we have a following
<iframe> element in our
<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
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"); element.style.color = "green";
In the example above, we have accessed the first
<p> element from an Iframe and changed its color to
Similarly, we can access and modify other elements in the iframe using
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).