1. References between the FORM and its elements
  2. Labels
  3. Elements

HTML Forms is an often guest in JavaScript-enabled sites. There are few tricks in working with it.

References between the FORM and its elements

There are additional helper links between DOM elements, besides hierarchy. They are described in DOM 2 standard.

All forms can be accessed by name using document.forms collection:

<form name="person-form">
  <input name="age" type="text">

  var form = document.forms['person-form']

A form references all elements in array-like collection:

var form = document.forms['person-form']
var ageInput = form.elements[0]

Note that the collection is numbered, not named.

A form element always keeps a backreference to the form in the corresponding property:

var form = document.forms['person-form']
var ageInput = form.elements[0]
alert( ageInput.form === form ) // true

So, form and it’s elements reference each other. These additional links are very convenient to keep things simple and evade calling extra document.getElementsBy....


Labels are very important to build proper interaction. When a user clicks on the label, the browser treats it as a click on the corresponding element.

Are you smart?
<label>Yes, sure! <input type="radio" name="smart" value="yes"></label>
<label>No, that's not about me <input type="radio" name="smart value="no"></label>

In the example above, there is no need to click on the form element itself. Clicking “Yes” or “No” text will do, because of label.

Sometimes wrapping an element inside LABEL is impossible. There is a for attribute to handle such case.

The label can be put separately but contain id of it’s tag in for attribute:

  <td><label *!*for="smart-yes"*/!*>Yes, sure!</label></td>
  <td><input type="radio" name="smart" value="yes" *!*id="smart-yes"*/!*></td>
  <td><label *!*for="smart-no"*/!*>No, that's not about me</label></td>
  <td><input type="radio" name="smart" value="yes" *!*id="smart-no"*/!*></td>

Again, clicking on the text in the example above will turn on the corresponding radio.