简体   繁体   中英

Access html form element, inside iframe without id/name

I have the following code-structure (nested HTMLs, although that probably doesn't make much of a difference)

<html>
    <body>
        <iframe>
            <html>
                <form id="loginForm" name ="loginFormName">
                    <input id ="name" name ="username">
                    </input>
                </form>
            </html>
        </iframe>
    </body>
</html

I tried it by accessing the input field via:

document.getElementById("name");
document.loginFormName.username;

But I believe the iFrame hinders me to access the elements. However, somehow accessing the iFrame first:

document.getElementByTagName("iframe).getElementById("name");

does not yield any results other than "undefined".

Help is much appreciated, I would like to auto-set the value of the input field and auto-submit the form. (form.submit). I have no preference regarding Javascript or JQuery.

You can use .contents() for that.

The contents( ) method finds all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.

$('iframe').contents().find('input')

If you want to submit the form, you can use this.

$('iframe').contents().find('form').submit();

Sample Fiddle demo to show how content in an iframe is accessed by contents( ) .

Accessing an element of an iframe is very easy.

You should use the following syntax for access input element & form submit:

$('iframe').contents().find('input'); //Form Element access

$('iframe').contents().find('#loginForm').submit(); //Form submit code

Hope it helps to resolve your query!

If your iframe is in the same domain as your parent page you can access the elements using document.frames collection.

give any id to your iFrame and replace myIFrame with your iFrame id

window.frames['myIFrame'].document.getElementById('name')

If your iframe is not in the same domain the browser should prevent such access for security reasons.

The problem is you are loading your iframe incorrectly.

  <div class="main"> <iframe src="iframecontent.html"> </iframe> </div> <!--iframecontent.html :--> <html> <body> <form id="loginForm" name ="loginFormName"> <input id ="name" name ="username"> </input> </form> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM