Joseph Michael Pesch
VP Programming

JavaScript getElementsByClassName() Function

by 24. February 2010 16:09

Function from: http://robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/

function getElementsByClassName(className, tag, elm){
  var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
  var tag = tag || "*";
  var elm = elm || document;
  var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
  var returnElements = [];
  var current;
  var length = elements.length;
  for(var i=0; i<length; i++){
    current = elements[i];
    if(testClass.test(current.className)){
      returnElements.push(current);
    }
  }
  return returnElements;
}

Tags:

JavaScript

Comments are closed