How to use document.getElementByName and getElementByTag?

getElementById returns either a reference to an element with an id matching the argument, or null if no such element exists in the document.

getElementsByName() (note the plural Elements) returns a (possibly empty) HTMLCollection of the elements with a name matching the argument. Note that IE treats the name and id attributes and properties as the same thing, so getElementsByName will return elements with matching id also.

getElementsByTagName is similar but returns a NodeList. It's all there in the relevant specifications.


  • document.getElementById('frmMain').elements
    assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a name attribute in IE, please add ID to the element if you want to use getElementById

  • document.getElementsByName('frmMain')[0].elements
    will get the elements of the first object named frmMain on the page - notice the plural getElements - it will return a collection.

  • document.getElementsByTagName('form')[0].elements
    will get the elements of the first form on the page based on the tag - again notice the plural getElements

A great alternative is

  • document.querySelector("form").elements
    will get the elements of the first form on the page. The "form" is a valid CSS selector

  • document.querySelectorAll("form")[0].elements
    notice the All - it is a collection. The [0] will get the elements of the first form on the page. The "form" is a valid CSS selector

In all of the above, the .elements can be replaced by for example .querySelectorAll("[type=text]") to get all text elements

Tags:

Javascript