How to get id of element in an iframe?

Member

by kadin , in category: HTML & CSS , 6 days ago

How to get id of element in an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 5 days ago

@kadin 

To get the id of an element within an iframe, you can use the following steps:

  1. Get the reference to the iframe element using JavaScript:
1
var iframe = document.getElementById('iframeId');


  1. Access the contentDocument of the iframe to get the document object of the iframe's contents:
1
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;


  1. Once you have the document object of the iframe's contents, you can get the element within the iframe using standard DOM methods like getElementById, getElementsByClassName, etc. For example, to get the id of an element with id 'elementId' within the iframe:
1
2
var elementId = iframeDoc.getElementById('elementId').id;
console.log(elementId);


This will log the id of the element within the iframe to the console.


Please note that the Same Origin Policy applies to iframes, so you can only access the contents of an iframe if it is on the same domain as the parent page.