Sunday, March 06, 2005

Correction to getElementsByClass()

The old getElementsByClass() function listed under "Reverse Archives" works only on Internet Explorer. I’ve written a new one using DOM syntax, so if you want cross-browser support, use this code instead:


function getElementsByClass(nm,nd)
{
var n=new Array(0);
if(!nd)
{
nd=document.body;
if(nd.className==nm)
n.push(nd);
}
with(nd)
{
for(var i=0; i<childNodes.length; i++)
{
if(childNodes[i].nodeType==1)
{
if(childNodes[i].className==nm)
n.push(childNodes[i]);
if(childNodes[i].childNodes.length)
n=n.concat(getElementsByClass(nm,childNodes[i]));
}
}
}
return n;
}