Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 909
Magnus Smith Avatar asked Jan 21 '09 13:01

Magnus Smith


3 Answers

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.

like image 157
Aron Rotteveel Avatar answered Nov 12 '22 12:11

Aron Rotteveel


Why not just use:

var nodesForm = node.form;

? It works on FF3, FF4, google chrome, Opera, IE9 (I tested myself)

like image 9
brunoais Avatar answered Nov 12 '22 12:11

brunoais


Guess you have to iterate through all elements then. You can try using jQuery:

$("input").parent("form")

http://docs.jquery.com/Traversing/parent#expr

like image 7
Deniss Kozlovs Avatar answered Nov 12 '22 10:11

Deniss Kozlovs