Reputation: 2143
I'm dealing with forms using Javascript for validation. For the sake of organizing and formatting the inputs, I need to use div
, table
, span
, etc. That causes a problem for me when I'm trying to get all the form information. Right now, I have a script that loops through all children of the parent (form), and does things accordingly. Unfortunately, because those pesky span
, div
, table
, tr
, and td
elements are all involved now, I can't get to the inputs using .childNodes
. How should I go about doing this?
Upvotes: 0
Views: 265
Reputation: 413996
The "elements" property of a form element gives a list of all inputs (etc.) in the form. That is,
var form = document.forms[0]; // or getElementById() ..
var elements = form.elements;
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
// do something with form element
}
It doesn't matter how many non-form wrapper elements are in the form, so this works regardless of your HTML markup. edit — this also works in old browsers that don't support the "querySelector" APIs.
Upvotes: 1
Reputation: 20225
Use querySelectorAll
:
document.querySelector('#parentElement').querySelectorAll('input')
Documentation: querySelector, querySelectorAll.
Both functions can be run on elements as well. Browser compatibility is in the docs.
Upvotes: 0
Reputation: 4192
User the :input
selector: (http://api.jquery.com/input-selector/)
Upvotes: 0