How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="https://stackoverflow.com/questions/1452871/iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what’s inside the iframe src.

Leave a Comment