This paragraph's class is "test1" and the ID is "para-1." You'll see why I tell you that at the end of this page.

If you're like me, there are times when you want to find one or all elements with a certain className. The DOM provides getElementById, getElementsByTagName, and the non-standard getElementsByName but not getElementsByClassName. Any JavaScript programmer worth their salt can do something with the available methods. But, having a getElementsByClassName method available can be convenient. (This paragraph has class test1 and ID explanation -- you'll see :).

Well, you can add your own! JavaScript can add methods or properties to any DOM object just by making the assignment.

Two approaches are presented here. (Also check out the Enhanced version for additional options.)

The first approach uses an annonymous function to assign code to as a method of an object. The second declares a function and then assigns it as a method of a DOM object, or calls it with a reference to a DOM object using the function methods call or apply. Either way creates a new method for an object or calls the function as if it were a method of the object. A method like our getElementsByClassName typically would be used as a method of the document object, but can be a methhod of any HTML element (tag).

Using an annonymous function:
document.getElementsByClassName = function(class_name) {
    var docList = this.all || this.getElementsByTagName('*');
    var matchArray = new Array();

    /*Create a regular expression object for class*/
    var re = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
    for (var i = 0; i < docList.length; i++) {
        if (re.test(docList[i].className) ) {
            matchArray[matchArray.length] = docList[i];
        }
    }

	return matchArray;
}//eof annonymous function


Using a function:
function cstmGetElementsByClassName(class_name) { var docList = this.all || this.getElementsByTagName('*'); var matchArray = new Array(); /*Create a regular expression object for class*/ var re1 = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)"); for (var i = 0; i < docList.length; i++) { if (re1.test(docList[i].className)) ) { matchArray[matchArray.length] = docList[i]; } } return matchArray; }//eof cstmGetElementsByClassName
Usage:
[document|tagRef].getElementsByClassName = cstmGetElementsByClassName;
call:
var array = [document|tagRef].getElementsByClassName("class-name"); Example: document.getElementsByClass = cstmGetElementsByClassName; var elementList = document.getElementsByClass("targetClass"); Or, use Techniques to Extending HTML Elements
call:
Example: var elementList = [document|tagRef].getElementsByClass("targetClass");

The working part of the code is the same in either case. The key word this is a reference to the object to which the function is assigned. In the example above, the document object.

The second approach is a question of managing the meaning of the key word this. We can assign our function to an object as a method and this will refer to the object. Alternatively we can use the JavaScript call or apply methods providing the object that this will refer to. Do this to reduce the number of elements retrieved or to narrow the part of the document affected by the action taken on the elements retrieved. For example:

    e = document.getElementById("html-elem");
    e.getElementsByClassName = cstmGetElementsByClassName;
    var array = e.getElementsByClassName("class-name");
or
    var elem = document.getElementById("html-elem");
    cstmGetElementsByClassName.call(elem, "class-name");
optionally
    cstmGetElementsByClassName.apply(elem, ["class-name"]);

Here "html-elem" is the ID for...let's say a DIV, this restricts the range of tags retrieved to descendents of that element—that DIV—and not the whole document.

This works because getElementsByTagName (and IE's all), which get the initial array of elements to check, is a method of all HTML elements (tags). It is most frequently seen as a method of the document; however, it can be elementRef.getElementsByTagName(tag)

The getElementsByClassName method is basic JavaScript executing the following steps.

  1. Fill an array of all elements in the document (or object of which it is a method) using the universal tag name (*) asterisk
  2. Create an empty array to hold references to the elements that meet our criteria
  3. Create a regular expressions to match the class name of interest.
  4. Step through the list of elements retrieved in step 1 assigning those with the required class name to the array created in step 2.
  5. Return the array of matches

IE5 Hack: Special consideration is given to IE5/Win. It does not support the the universal tag name * (asterisk) so the IE collection all is used instead of getElementsByTagName, which is otherwise supported in IE.

(This paragraph also has class test1, but you'll have to guess the ID.)

The meta-character \b, indicating a word boundary, is not used in the regular expression pattern because a dash, which is legal in class names, marks a word boundry the same as a space does. This could cause incorrect matches. Instead two subsets with optional matching characters are used. (?:^|\s) matches the beginning of the string or a space and (?:\s|$) matches a space or the end of the string. The ?: makes the subsets non-capturing so the regular expression is slightly more efficent. The double back solidus or virgule, \\, is required by JavaScript so one back virgule will be passed to the method ReqExp.

The array method push was not used to add matches to matchArray because it is not supported in older browsers.

Click on the button to find the elements that have a className of test1. The count and their IDs will be displayed. This paragraph is one (class test1) and its ID is dummy-paragraph.