Forum Moderators: open

Message Too Old, No Replies

document.getElementsByClassName

A useful function for finding tags by their css class name.

         

lobo235

10:40 pm on Sep 25, 2006 (gmt 0)

10+ Year Member



I was looking for a good function to get objects from the DOM by their class name. As you already know, the JavaScript language does not have a built-in function that allows you to do this. Many people have written their own function to do this but I couldn't find one that was solid so I wrote my own. The problem with most of them is that they would match partial class names or not work at all if your elements have multiple class names such as class="green small". The function I wrote handles all the cases I could think of.

Here is the function. I am open to any feedback or questions you may have dealing with this code:

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)
retVal.push(elements[i]);
}
}
else if(elements[i].className == clsName)
retVal.push(elements[i]);
}
return retVal;
}

daveVk

2:57 am on Sep 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It may be usefull to to bring tagName out as an optional second parameter as optimization for when it is known, going thru all elements can be slow. Also can capitalize on how split works to remove single word check I think.

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

Fotiman

6:09 pm on Sep 27, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I prefer the Yahoo UI Library's Dom Collection [developer.yahoo.com] for getting elements by class name.