getElementByClass 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.

It's implementation is quite simple and all you need to do is modify the last line to inact changes in your webpage (via the DOM).

<script>
//Create an array of tags

var allPageTags = new Array();

function modifyElementbyClass(theClass) {
    //Populate the array with all the page tags
    var allPageTags=document.getElementsByTagName("*");

    //Cycle through the tags
    for (i=0; i<allPageTags.length; i++) {
        //Pick out the tags with our class name
        if (allPageTags[i].className==theClass) {
            //Manipulate this in whatever way you want
            allPageTags[i].style.display='none';
        }
    }
}
</script>

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

Back to home page