
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.
Popularity: 100% [?]


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.
November 14th, 2008 at 11:16 am
Thanks for the tip, Benj! Ran into this problem recently with multiple objects sharing a single class and had no object handle method to batch manipulate them, unless such a function also exists in a Javascript framework.
January 28th, 2009 at 11:01 am
Thank you man.
February 18th, 2009 at 4:13 pm
cool thanks!
March 16th, 2009 at 7:11 pm
Neat-o. I need this for a wiki, and… it seems like it’s already there. ?:-S
June 10th, 2009 at 7:03 pm
Thanks for the code, helped me out a lot on what I was trying to accomplish
June 30th, 2009 at 9:51 pm
Nice script, but I can’t seem to make it work in Firefox or google chrome.
Any suggestions?
John
December 30th, 2009 at 8:48 pm
Not sure what the problem is John, but in my experience, this works on Firefox and Chrome.
February 12th, 2010 at 7:32 am
Great litle script – been looking for something like this for a fair while today and not being too hot on jscript (more of a php sort of chap) I’ve been getting clogged down in all sorts of convoluted and hard to follow scripts.
This has nice simple ‘one step at a time’ logic and goodcomments.
Many thanks.
February 26th, 2010 at 7:07 pm
FINALLY!!! I found it!!! THANK YOU!!!
March 4th, 2010 at 11:11 am
thank you very much! I will use it!
June 13th, 2010 at 2:37 am
I don’t have a problim with this script John, it’s working fine on FF and Chrome, i’m using this
window.onload = function() {
var allATags = new Array();
var allATags = document.getElementsByTagName(‘A’);
for (i=0; i < allATags.length; i++) {
if (allATags[i].className == 'noshow') {
allATags[i].onclick = function(){ return false; };
}
}
}
July 22nd, 2010 at 10:10 am
This is a great little script, thanks so much for posting man!
November 8th, 2010 at 11:01 am
This is exactly what I needed. Tahnks!
December 3rd, 2010 at 8:41 am
I modified it so that you can specify the tag type and it will work similar to getElementsById, but it will return an array of items
/* function name: getElementByClass
* purpose: gets all elements based off of a class
* input: String, String (optional)
* output: none
*/
function getElementsByClass(theClass, classType)
{
//pulls the elements based off of their tag
//if one is not specified, it will pull everything
var allHTMLTags=document.getElementsByTagName((classType?classType:’*'));
//temp array that is going to grab our elements
var returnerArray = new Array();
//go through the main array of elements
for (var i=0; i<allHTMLTags.length; i++)
{
//if the element is within the class we want
//we will add it to our array
if (allHTMLTags[i].className==theClass)
{
returnerArray.push(allHTMLTags[i]);
}
}
//send the array back to the calling function
return returnerArray;
}
February 4th, 2011 at 11:20 pm
Hi,
I’m trying to figure out how to change the background of multiple div’s (of class “blank”) with a single link.
var allHTMLTags = new Array();
function changeDivBG(imgName) {
var allHTMLTags=document.getElementsByTagName(“blank”);
for (i=0; i<allHTMLTags.length; i++) {
if (allHTMLTags[i].className==imgName) {
allHTMLTags[i].style.backgroundImage = "url("+imgName+")";
}
}
}
on the site I have multiples of this div
and one of this:
Happy
But it’s not working. I would appreciate any help!
Thanks in advance!
February 20th, 2011 at 3:57 am
Thanks, for good idea, as i understand function getElementByClass(‘theClass’) must be called after the last culry brace?
April 25th, 2011 at 9:46 am
Hi!
I’m just a newbie in JS. Could you write a simple but real example to display how we can getElementByClass? I’ve tried out for many times but failed.
My 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.
document.className('whatever').style.color='red';
}
}
}
div
I want to have the div with class name “whatever” that its text “div” is to be changed to red in colour.
Could you show me how we can achieve it?
Thank you!
June 4th, 2011 at 4:49 am
Thanks a lot for this script!
For those having trouble to make it work, I suggest looking at these characters: ‘ and ” because sometimes they paste a little stylish and are not recognized as code.
June 24th, 2011 at 10:41 pm
how about making ur life 100 times simpler by just using JQuery?
September 4th, 2011 at 8:06 am
For multiple class names try this instead:
if (allHTMLTags[i].className.match(/(^| )theClass( |$)/))
this means it starts with the class name, or there is a space before the class name, and it ends with the class name, or there is a space after the class name.