Archive for the 'javascript' Category

Find all form elements with Javascript DOM

Wednesday, May 31st, 2006

Here’s a quick way of finding all the form elements on a given page using the DOM-Friendly getElementsByTagName function. Because it works on the Document Object Model, it’ll work on any node in the document. That means you can find the form elements within a given form, fieldset, div or any element on the page. That gives it an advantage over the boring old document.forms array, but it does mean you’ll need a DOM-Compatible browser, so no Netscape 3 for you. It might be a nice addition to your unobtrusive javascript arsenal.

The Code:

function getAllFormElements( parent_node ) {
if( parent_node == undefined ) {
parent_node = document;
}
var out = new Array();
formInputs = parent_node.getElementsByTagName("input");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
formInputs = parent_node.getElementsByTagName("textarea");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
formInputs = parent_node.getElementsByTagName("select");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
formInputs = parent_node.getElementsByTagName("button");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
return out;
}

The Explanation

Just call it without parameters to get all the form elements on the current page, or pass it a DOM node to find only elements that are descendants of that node. Easy as that.

The function calls getElementsByTagName 4 times so that we get all of the different form element tags. It pushes the results of those calls onto an array. getElementsByTagName returns an HTMLCollection not an array, so pushing all the elements onto the array lets us do even more with the results.

Going Further

We can use this basic technique to get any set of tags:

function getElementsByTagNameMultiple( tag_names, parent_node ) {
if( parent_node == undefined ) {
parent_node = document;
}
var out = new Array();
for( var i = 0; i < tag_names.length; i++ ) {
elementsFound =
parent_node.getElementsByTagName(tag_names[i]);
for (var j = 0; j < elementsFound.length; j++)
out.push( elementsFound.item(j) );
}
return out;
}

Which makes my get form elements function a little simpler:

function getAllFormElements( parent_node ) {
return getElementsByTagNameMultiple(
[ 'input', 'textarea', 'select', 'button' ]
);
}

I hope you find this useful. If you have any comments suggestions or feedback leave a comment. I tested these in Firefox and Safari. Your mileage may vary.