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

How to Access Elements Inside an iFrame?

DDD
Release: 2024-12-13 21:24:18
Original
342 people have browsed it

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;
Copy after login

or, more simply:

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
Copy after login

Once you have obtained the innerDoc, you can access the DIV element by its ID using:

innerDoc.getElementById('divId');
Copy after login

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: [