document.getElementsByClassName的理想实现

来自: 司徒正美 blog

http://www.cnblogs.com/rubylouvre/archive/2009/07/24/1529640.html

 

 

先看一下各浏览器对document.getElementsByClassName的支持

当然如果游览器原生支持,就用原生的。

各主流游览器的支持情况 IE8 IE7 IE6 FF3 FF2 Saf3 Op9 Op10 Chrome
N N N Y N Y Y Y Y

 

(中间省略.......)

综合以上方案,我得出了一个最理想的实现——兼容IE5,让后面两个参数是可选的,能原生的原生,利用字面量与倒序循环提高效率……

//查找一网页中5007个类名为“cell”的元素,IE8历时1828 ~ 1844毫秒,
//IE6为125 ~ 172毫秒,IE8为93 ~ 94毫秒,FF3.5为0~1毫秒,opera10为0毫秒,Chrome为1毫秒,
//safari4为0毫秒
var getElementsByClassName = function (searchClass,node,tag) {
     if (document.getElementsByClassName){
         return  document.getElementsByClassName(searchClass)
     } else {   
         node = node || document;
         tag = tag || '*' ;
         var returnElements = []
         var els =  (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag);
         var i = els.length;
         searchClass = searchClass.replace(/\-/g, "\\-" );
         var pattern = new RegExp( "(^|\\s)" +searchClass+ "(\\s|$)" );
         while (--i >= 0){
             if (pattern.test(els[i].className) ) {
                 returnElements.push(els[i]);
             }
         }
         return returnElements;
     }
}

用法:

var collections = getElementsByClassName( "red" );

但它还是不如原生的getElementsByClassName,不能同时检索多个class

< h2 class = "red cell title" >安装支持</ h2 >
 
< span class = "cell red  " >jjj</ span >
 
< div class = "filament_table  red cell" >这是DIV</ div >
 
#利用 var dd = getElementsByClassName("cell red") ,这三个元素都应该能被检索到!

因此,最最终的方案为:

var getElementsByClassName = function (searchClass, node,tag) {
   if (document.getElementsByClassName){
     var nodes =  (node || document).getElementsByClassName(searchClass),result = [];
       for ( var i=0 ;node = nodes[i++];){
         if (tag !== "*" && node.tagName === tag.toUpperCase()){
           result.push(node)
         } else {
           result.push(node)
         }
       }
       return result
     } else {
       node = node || document;
       tag = tag || "*" ;
       var classes = searchClass.split( " " ),
       elements = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag),
       patterns = [],
       current,
       match;
       var i = classes.length;
       while (--i >= 0){
         patterns.push( new RegExp( "(^|\\s)" + classes[i] + "(\\s|$)" ));
       }
       var j = elements.length;
       while (--j >= 0){
         current = elements[j];
         match = false ;
         for ( var k=0, kl=patterns.length; k<kl; k++){
           match = patterns[k].test(current.className);
           if (!match)  break ;
         }
         if (match)  result.push(current);
       }
       return result;
     }
   }

 

你可能感兴趣的:(document)