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;
}

4 comments:

Anonymous said...

I don't think .push used in the code sample works in ie5

Brian said...

In what operating system? I can forgive you if you're still using IE 5/MAC, but if Windows, why? Internet Explorer is up to version 6, and they're going to release 7 later this year.

if(Mac)
 switchTo(other browser);
else
 upgrade(MSIE);

abhi said...
This comment has been removed by the author.
abhi said...

http://pitfalls.wordpress.com/2008/07/07/querying-it-jquery-way-getelementsbyclass/