DOM getElementsByTagName Method for Bulk Element Formating

Page content

Background

Setting common attributes on multiple elements can be repetitive and time consuming.This can be automated on a page load if the fields are gathered as a Document Object Model (DOM) collection. For example, a web site needs to collect user information on a web page with a multitude of text input elements or the developer wants to set a distinct background color on the currently selected input and change it back to the default background color when the element loses focus.

The getElementsByTagName(tagName) Method

The getElementById(tagID) applies only to the document object while the getElementsByTagName(tagName) applies to any DOM object. The sample below has a blockquote element wrapped around several input elements. We’ll use the document.getElementById(tagID) method to get the blockquote tag as an object; and apply getElementsByTagName(“input”) to get the collection1 of input elements.

In the sample below, we’d like the active input element to be highlighted with a lightyellow background when it is selected; and then turn back to the default white when the user tabs to the next input element. To accomplish this it uses the onfocus and onblur attributes of the input elements.

1A collection is more than an array. The getElementsByTagName method returns a collection that has the length property, and the array of elements of the parent object the method was applied to. Enumerating this collection may vary with the browser but the array of elements can be accessed the same way because they are indexed by integer. This may sound confusing but the point is that a collection is not the same as an array.

Code View

Paste the code below into your editor

First Name 

Last Name 

Address1 

Address2 

Email 

This post is part of the series: Web Design using DHTML and the DOM

Creating web sites with DHTML based on the DOM can increase server performance, lower bandiwdth utilization and solve most cross-browser compatibility issues.

  1. Getting Elements Using the HTML DOM and JavaScript
  2. Applying Events to DHTML Web Pages Using Javascript and the DOM
  3. Validating Input at the Client: Check for blank or required fields
  4. Validating Input at the Client: trim the field
  5. Validating Input at the Client: check numeric value fields
  6. Leveraging CSS Styles
  7. DOM getElementsByTagName Method for Bulk Element Formating
  8. Unraveling the JavaScript Switch Statement