Javascript - getElementsByName Home

Javascript - getElementsByName
20/01/2006 posted by Kevin S
So whats in a name? Well an awful lot.

Recently I was developing some code to hide and show html tables using javascript and uncovered a little used javascript method getElementsByName().

Its supported by both Internet Explorer and Firefox since it is part of the DOM Level 1 specification.

Unfortunately theres a problem. From the Html 4.01 Spec, only the A, APPLET, BUTTON, FORM, FRAME, IFRAME, IMG, INPUT, OBJECT, MAP, META, PARAM, TEXTAREA and SELECT are supported which means that you can't just name all your divs, spans or rows with the same name and use getElementsByName() to return an array of items.

This is extremely annoying since Firefox does allow this to occur, but Internet Explorer duly follows the specification( for a change).

To get around the problem you need to uniquely id all rows that you want to show and hide.
heres a code frag - hope it helps.

In the Stylesheet have:

	.show { display:marker; }
	.hide { display:none;   }	

In the Javascript have:
        function hideSelects( val, item )
	  for( loop=0;loop<=item;loop++ )
	     var elem = document.getElementById( val+loop );
	     if( elem )
	       if( elem.className=="" || elem.className=="show")
	          elem.className = 'hide';
	          elem.className = 'show';
	     } /* if */
	  } /*for*/
and in the html:

	<h1 onclick="hideSelects('row', 2)">clickme!</h1>

	  <tr id="row0">
	    <td>some text1</td>
	  <tr id="row1">
	    <td>some text2</td>
	  <tr id="row2">
	    <td>some text2</td>