[Javascript] finding an element in the DOM sea

Paul Novitski paul at novitskisoftware.com
Tue Jan 31 01:50:57 CST 2006


At 08:58 PM 1/30/2006, Jonathan Gold wrote:
>2. Obviously I have fallen (in a short time really: can't be more 
>than 3-4 years) into, as you put it, the _old_ school. Is there a 
>text(s) that you could recommend that would put me up to speed again?

Gecko DOM Reference
http://developer.mozilla.org/en/docs/Gecko_DOM_Reference

Core JavaScript Guide
http://www.croczilla.com/~alex/reference/javascript_guide/


>1. I can get elements by ID or by TagName. Can I retrieve them by 
>Class. I tried but couldn't get it.

There's no direct method for collecting elements by class in 
JavaScript/DOM, but you can accomplish it by searching through all 
the page elements examining their classNames.  Here's my function for 
doing this:

//=========================
function getElementsByClassName(argClassName, argTagName)
//=========================
// pass:        argClassName = class you're seeking
//              argTagName = [optional] tag name to limit search
//
// returns: array of matching elements
{
         // we'll be searching for the requested class name,
         // optionally bracketed by spaces to handle multiple classes
         var reClassMatch = new RegExp("(^| )" + argClassName + "( |$)");

         // prepare to return the results in an array
         var aResult = new Array();

         // default = search all page elements
         var sTagName = "*";

                 // if one tag was requested, limit the search
                 if (argTagName) sTagName = argTagName;

         // get array of all elements [with matching tag if requested]
         var aEls = document.getElementsByTagName(sTagName);

         // collect elements with matching classNames
         for (var iEl=0; iEl < aEls.length; iEl++)
         {
                 if (reClassMatch.test(aEls[iEl].className))
                 {
                         aResult[aResult.length] = aEls[iEl];
                 }
         }

         // return array of found elements or null
                 if (aResult.length == 0) aResult = null;
         return aResult;
}

You can use it like so:

         // get all SPANs with the className "frog"
         var aSpans = getElementsByClassName("frog", "span");

         // get all page elements (any tag) with the class "button"
         var aButtons = getElementsByClassName("button");

                 // check for results
                 if (!aButtons) alert("No button class found");

Regards,
Paul  




More information about the Javascript mailing list