javascripthtmlwebforms

Finding the FORM that an element belongs to in JavaScript


How can I find out which FORM an HTML element is contained within, using a simple/small bit of JavaScript? In the example below, if I have already got hold of the SPAN called 'message', how can I easily get to the FORM element?

<form name="whatever">
    <div>
        <span id="message"></span>
    </div>
</form>

The SPAN might be nested within other tables or DIVs, but it seems too long-winded to iterate around .parentElement and work my way up the tree. Is there a simpler and shorter way?

If it wasn't a SPAN, but an INPUT element, would that be easier? Do they have a property which points back to the containing FORM? Google says no...


Solution

  • The form a form element belongs to can be accessed through element.form.

    When the element you are using as reference is not a form element, you'd still have to iterate through the parentElement or use some other kind of selector.

    Using prototype, you could simplify this by using Element.up():

    $(element).up('form');
    

    Other answers to this question have pointed out how to do the same in jQuery.