Get list of all input objects using JavaScript, without accessing a form object

Jeremy Gwa picture Jeremy Gwa · Feb 6, 2010 · Viewed 132.8k times · Source

I need to get all the input objects and manipulate the onclick param.

The following does the job for <a> links. Looking for something like this for input tags.

for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
  var link = unescape(ls[i].href);
  link = link.replace(/\\'/ig,"#");
  if(ls[i].href.indexOf("javascript:") == -1)
  {
    ls[i].href = "javascript:LoadExtern(\\""+link+"\\",\\"ControlPanelContent\\",true,true);";
  }
}

Answer

T.J. Crowder picture T.J. Crowder · Feb 6, 2010

(See update at end of answer.)

You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it:

var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

There I've used it on the document, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:

var container, inputs, index;

// Get the container element
container = document.getElementById('container');

// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

...but you've said you don't want to use the parent form, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).


Update: getElementsByTagName is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input elements?

That's where the useful querySelectorAll comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:

var checkboxes = document.querySelectorAll("input[type=checkbox]");

You can also use it at the element level. For instance, if we have a div element in our element variable, we can find all of the spans with the class foo that are inside that div like this:

var fooSpans = element.querySelectorAll("span.foo");

querySelectorAll and its cousin querySelector (which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.