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