Home >Web Front-end >JS Tutorial >How to Access Elements Inside an iFrame?
Accessing Elements Within an iFrame
Retrieving elements from within an iFrame can be necessary for manipulating the content or gathering data from the embedded frame. Here's how to do it:
Method:
To get a DIV element from within an iFrame, use the following code:
var iframe = document.getElementById('iframeId'); var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
or, more simply:
var iframe = document.getElementById('iframeId'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
Once you have obtained the innerDoc, you can access the DIV element by its ID using:
innerDoc.getElementById('divId');
Note:
It's crucial to ensure that the iFrame is located on the same domain as the parent page to gain access to its content. Cross-site scripting is prevented by the same-origin policy.
References:
The above is the detailed content of How to Access Elements Inside an iFrame?. For more information, please follow other related articles on the PHP Chinese website!