
A colleague of mine at work, Patrick Alcisto, asked me how a getElementByClass is done in JavaScript since getElementByID exists in JavaScript but getElementbyClass does not exist. And I have been using a standard script ever since 2004 that I just always have handy in my previous work, but sometimes, looking and remembering which websites I applied it on takes some time. So just to make it easy for me find the code when I need it, might as well post it on my blog so it is easy to find. Check the sample getElementsByClass code below:
The getElementByClass example code.
/* getElementByClass
/**********************/var allHTMLTags = new Array();
function getElementByClass(theClass) {
//Create Array of All HTML Tags
var allHTMLTags=document.getElementsByTagName(”*”);//Loop through all tags using a for loop
for (i=0; i<allHTMLTags.length; i++) {//Get all tags with the specified class name.
if (allHTMLTags[i].className==theClass) {//Place any code you want to apply to all
//pages with the class specified.
//In this example is to “display:none;” them
//Making them all dissapear on the page.allHTMLTags[i].style.display=’none’;
}
}
}
Just a brief explanation to the less knowledgeable in JavaScript how this sample code of getElementByClass works is you are simply taking note of all HTML tags present on the page. And going through a loop check each tag, placing them in an array. Then for each member of the array, check if any of them has a class name. And check if it is the class you are specifying.
Feel free to use the code above and share to the world.
Since this is a function, you just tie it up to any event like an onclick or onmouseover on within other functions. Here is an example where someone clicks on a link and will apply the JavaScript code in getElementByClass to a div.
<div class=”whatever”>…</div>
…
<a href=”…” onclick=”getElementByClass(’whatever’);”><img src=”…”></a>
Just a small note, not all browsers support all JavaScript versions. This script may not work in older browsers. Where getElementByID will not work either. Another note is if you did a copy and paste to the codes above, be sure to change the doublequotes and ( ” ) single quotes ( ‘ ) with the plain text ones so you get no errors.

December 8th, 2007 at 1:31 pm
What if the element has multiple classes?
December 10th, 2007 at 7:19 pm
sorry to interrupt u, this script block surely can run to what u expect, but have u thought this situation : there are lots of tag in one page, the page will appear very very slowly, u can test it.
December 26th, 2007 at 4:10 pm
Hey this has been very helpful, thanks for posting this! I have already had to use this script a couple of times.
July 14th, 2008 at 3:30 am
hi
i would like to advert on your blog. can u pls get back to me so we can talk more about.
thanks
ps: sorry for posting it here, but wasn’t found any email address.