Skip to content Skip to sidebar Skip to footer

Find Form That Contains Element?

I have an element inside a form, there might be many elements between them. Having a variable pointing to my element, I want to know how to get the parent form in a variable. EG: &

Solution 1:

It's pretty simple to do this:

var lookup = element;
while(lookup && lookup.nodeName != "FORM") lookup = lookup.parentNode;
if( lookup) {
    // lookup if your form
}

I have this in a function in my projects, called "findParent", that accepts a callback to test if the element is the one I'm looking for.

Solution 2:

With HTML5 it would be

<input element>.form

fiddle

HTML5 - 4.10 FormsA form-associated element is, by default, associated with its nearest ancestor form element (as described below), but, if it is reassociateable, may have a form attribute specified to override this

Solution 3:

Javascript function to achieve this :

functionParentForm(element){ 
  var parent = elem.parentNode; 
  if(parent && parent.tagName != 'FORM'){
     parent = findParentForm(parent);
     }
  return parent;
}
var myForm = parentForm(myElement)

Post a Comment for "Find Form That Contains Element?"