getElementsByClassName and getElementsByNameEx

2007-11-30 @ 13:17#

ok, lots has been done to create getElementsByClassName functions for javascript. very handy and a welcome update coming in the next version of ECMAScript (or whatever it's called this week). I added that to the document object in my base library script to make sure it's always there handy for me. of course, i check to see if it's already defined since i am optimistic and hope that my code is still running the day the new version of JS appears in the wild [tee-hee].

the other additional function i added is getElementsByNameEx. the current version of this method only returns items that have the name attribute defined, not any elements that have name as an expando element. i know it's bad form to add name to DIV, SPAN and other items. but it happens (i inherited a lot of code like that). so this new method (>getElementsByNameEx) returns all the elements with the name attribute whether it's a native attribute or expando version. solves a bunch of problems for me!

ok, the code...

if(!document.getElementsByClassName)
{
  document.getElementsByClassName = function(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;
  };
}

if(!document.getElementsByNameEx)
{
  document.getElementsByNameEx = function(name, tag, elm)
  {
    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(current.getAttribute('name')==name){
        returnElements.push(current);
      }
    }
    return returnElements;
  };
}

code