getElementsByClass Javascript Function

Back to home page

As there is no method in javascript to access an element by class, this simple javascript function will allow you to do so on your pages.

Its implementation is quite simple and all you need to do is perform an action on each item in the returned array.

See a basic example. | See my real-world example.

<script>
function getElementsByClass(theClass) {
    var allPageTags = new Array();

    //Populate the array with all the page tags
    allPageTags=document.getElementsByTagName("*");
    var Elements = new Array();

    //Cycle through the tags
    var n = 0;
    for (i=0; i<allPageTags.length; i++) {
        //Pick out the tags with our class name
        if (allPageTags[i].className==theClass) {
            Elements[n] = allPageTags[i];
            n++;
        }
    }

    return Elements;
}
</script>

The above is quite handy if you want to do the same task to many objects (say, specific span or div tags) and don't want to give a unique id to all of them and send each id to a function.

See a basic example. | See my real-world example. | Back to home page



Your Rating      Overall Rating   

Comment on this Code

Your Name
Comment

Recent Comments

"Versions of function are available everywhere on the net. I just wanted to give it one more place to live." - Posted by Sean on Thursday Jul 3rd, 2008 at 7:29pm

"free preteen nude pics and videos" - Posted by osher on Monday Jul 7th, 2008 at 12:53am

"this is be cool 8) " - Posted by Yvvyqkms on Friday Jul 11th, 2008 at 12:18pm

"this is be cool 8) " - Posted by Yvvyqkms on Friday Jul 11th, 2008 at 12:18pm

"I`m happy very good site " - Posted by Pxqeoyuv on Monday Jul 14th, 2008 at 9:17am

"Very nice site!" - Posted by Pharm40 on Tuesday May 27th, 2008 at 9:25am

"magic story very thanks " - Posted by eblanned on Wednesday Sep 10th, 2008 at 3:05am

" " - Posted by Jimmi on Wednesday Sep 10th, 2008 at 3:05am

"Wonderfull great site " - Posted by deadman on Wednesday Sep 10th, 2008 at 3:05am

"This site is crazy :) " - Posted by Klymmuju on Saturday Sep 27th, 2008 at 10:04am