How to getElementByClass in Javascript – The Code

Thu, Nov 8, 2007

Code

getElementByClass - How to, sample code.

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.

This post was written by:

- who has written 146 posts on action online.

Started a career as a chemist. Worked in the industry and academe and pursued a master's degree in chemistry. Then one day, here I go, start a computer shop, then web company in 1999, won a few awards and just started a web career working on websites of various companies and making sure the websites work for them.

Contact the author

24 Comments For This Post

  1. Facedown Says:

    What if the element has multiple classes?

  2. ikaiser Says:

    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.

  3. Focale2 Says:

    Hey this has been very helpful, thanks for posting this! I have already had to use this script a couple of times.

  4. vlad Says:

    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.

  5. Glenn Batuyong Says:

    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.

  6. dialtahi Says:

    Thank you man.

  7. conor Says:

    cool thanks!

  8. A.H.M. Says:

    Neat-o. I need this for a wiki, and… it seems like it’s already there. ?:-S

  9. Daniel Wired Says:

    Thanks for the code, helped me out a lot on what I was trying to accomplish

  10. John Says:

    Nice script, but I can’t seem to make it work in Firefox or google chrome.

    Any suggestions?

    John

  11. Benj Arriola Says:

    Not sure what the problem is John, but in my experience, this works on Firefox and Chrome.

  12. DaveF Says:

    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.

  13. Jurgen Guthixx Says:

    FINALLY!!! I found it!!! THANK YOU!!!

  14. luis Says:

    thank you very much! I will use it!

  15. sve Says:

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

  16. Jude Says:

    This is a great little script, thanks so much for posting man!

  17. Ilia Says:

    This is exactly what I needed. Tahnks!

  18. Kevin Says:

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

  19. Kose Says:

    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!

  20. Kirill Says:

    Thanks, for good idea, as i understand function getElementByClass(‘theClass’) must be called after the last culry brace?

  21. Tin Says:

    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!

  22. Maryse Says:

    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.

  23. Asad Says:

    how about making ur life 100 times simpler by just using JQuery?

  24. Frank Says:

    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.

Leave a Reply