Diving down into an iframe rabbit hole.

How to target an element within the content of an iframe and when that is possible.

I have been needing, for a project, to resize an iframe as the container element within the iframe's content grows and shrinks.

For that, I would have to dive down into the page that was being brought-in and displayed in the iframe, and get the current height of that element.

This can only be done if that page comes from the same domain as the parent page. Something I talked about in another post.

If that's all good, you can get to the document of the iframe with

.contentDocument

Something like this:

iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const frameDocument = iframe.contentDocument;

Then it was just a case for me to dive down the rabbit-hole of nested elements, until I found the one I wanted. There were HTML collections along the way, the elements of which can be accessed thus:

.item(collection-array-position)

This was the particular path I had to follow:

const desiredElement = frameDocument.children.item(0).children.item(1).children.item(1).children.item(0).children.item(1);

Then it was just as case of getting the element's client height:

const usefulHeightMeasurment = desiredElement.clientHeight

Then I could reset the iframe height accordingly.

Nice!