Site Moved

This site has been moved to a new location - Bin-Blog. All new post will appear at the new location.


getElementsByClassName() Function for JavaScript

A very needed function for javascript - the getElementsByClassName(). Many versions of this function are floating around the net - and each with a different but similler name. Like document.getElementsByClass or getElementByClass or getElementByClassName etc. And as if that was not enough, I made one of my own. Call it like this - var anchors = getElementsByClassName("external","a");. This will return all the anchors that are in the 'external' class. Or use just var anchors = getElementsByClassName("external"); this will return all elements that are in the 'external' class.

//Get all the elements of the given classname of the given tag.
function getElementsByClassName(classname,tag) {
 if(!tag) tag = "*";
 var anchs =  document.getElementsByTagName(tag);
 var total_anchs = anchs.length;
 var regexp = new RegExp('\\b' + classname + '\\b');
 var class_items = new Array()
 for(var i=0;i<total_anchs;i++) { //Go thru all the links seaching for the class name
  var this_item = anchs[i];
  if(regexp.test(this_item.className)) {
 return class_items;
Filed Under.. Categories : Technorati Tags:

1 Comment:

Unknown said...

thank you a lot