The Netlobo logo - a Nevada desert landscape

Javascript document.getElementsByClassName

A useful function to help you manipulate the DOM easier than ever before

Published Feb 27, 2006 by lobo235
Last updated on May 19, 2009

In Javascript there are some useful functions that can be used to work with DOM stuff. You can use getElementById to find a specific element using its id or you can use getElementsByTagName to get all the elements of a specific tag type. One function that I have longed for while doing my own DOM manipulation is getElementsByClassName but this is not included in Javascript so I wrote my own. I know that other people have gone and done the same thing but my getElementsByClassName works better in certain cases and I will show you why. Here is my version of getElementsByClassName:

document.getElementsByClassName = function(clsName){
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
        else if(elements[i].className == clsName)
    return retVal;

Some of the other versions of this function have been written to simply search the entire class attribute of all the tags to see if it contains the class name passed into the function. This will probably work for most cases but consider the following example element.

<p class="green right"></p>

This p tag takes advantage of the fact that you can use multiple css selectors in the class attribute. The "green" css class and the "right" css class will both be applied to this p tag. Now, using some of the other getElementsByClassName functions that others have written, if you called the function with the class name parameter of "ri" it would match this p tag. Using the function I have provided above it will not because neither "green" or "right" equals "ri". The other implementations see that the word "right" has "ri" in it so it finds a match. This is not how I envisioned that the getElementsByClassName should work so I re-wrote it the way I wanted it.

9 comments for this article.

Other great Web Development and Programming articles on
Preventing MySQL Injection attacks with PHP
Passing information from Javascript to PHP
Checkbox Magic - Checking, Unchecking, and Inverting with Javascript