Home >Web Front-end >JS Tutorial >How to Access Elements Inside an iFrame?

How to Access Elements Inside an iFrame?

DDD
DDDOriginal
2024-12-13 21:24:18316browse

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:

  • MDN: [