Pin Me

DOM getElementsByTagName Method for Bulk Element Formating

written by: Carmelo Carbonara•edited by: Linda Richter•updated: 10/6/2008

This article provides an example on how to set attributes to a collection of elements by using the Document Object Model (DOM) getElementsByTagName() method. A sample is provided using JavaScript in the client's browser.

  • slide 1 of 3


    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.

  • slide 2 of 3

    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.

  • slide 3 of 3

    Code View

    Paste the code below into your editor

    <blockquote id="sampleBlock">

    First Name&nbsp;<input type="text" size="15" maxlength="15" />

    Last Name&nbsp;<input type="text" size="15" maxlength="15" />

    Address1&nbsp;<input type="text" size="15" maxlength="15" />

    Address2&nbsp;<input type="text" size="15" maxlength="15" />

    Email&nbsp;<input type="text" size="15" maxlength="15" />


    <script language="JavaScript" type="text/javascript">

    function domElement(objID){return document.getElementById(objID) ;}

    function domCollection(domObj,tagName){return domObj.getElementsByTagName(tagName) }


    for (i=0 ; i < inpFlds.length; i++)