Sometimes, wee want to access iframe elements with JavaScript.
In this article, we’ll look at how to access iframe elements with JavaScript.
How to access iframe elements with JavaScript?
To access iframe elements with JavaScript, we use the contentWindow
or contentDocument
property.
For instance, we write
<iframe id="one" src="iframe2.html"> </iframe>
to add an iframe.
Then we write
const iframeRef = (frameRef) => {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument;
};
const inside = iframeRef(document.getElementById("one"));
to define the iframeRef
function.
In it, we get the iframe’s document object with frameRef.contentWindow.document
or frameRef.contentDocument
.
Conclusion
To access iframe elements with JavaScript, we use the contentWindow
or contentDocument
property.