getElementByClassName some ways.

getElementByClassName some ways.

Tree Walker

An implementation using the DOM Level 2 Tree Walker methods. Builds a generic filter function and traverses through all elements.

document.getElementsByClass  =   function (needle) {
  
function  acceptNode(node) {
    
if  (node.hasAttribute( " class " )) {
      
var  c  =   "   "   +  node.className  +   "   " ;
       
if  (c.indexOf( "   "   +  needle  +   "   " !=   - 1 )
         
return  NodeFilter.FILTER_ACCEPT;
    }
    
return  NodeFilter.FILTER_SKIP;
  }
  
var  treeWalker  =  document.createTreeWalker(document.documentElement,
      NodeFilter.SHOW_ELEMENT, acceptNode, 
true );
  
var  outArray  =   new  Array();
  
if  (treeWalker) {
    
var  node  =  treeWalker.nextNode();
    
while  (node) {
      outArray.push(node);
      node 
=  treeWalker.nextNode();
    }
  }
  
return  outArray;
}

The Ultimate getElementsByClassName

Uses a pure DOM implementation, tries to make some optimizations for Internet Explorer.


function  getElementsByClassName(oElm, strTagName, strClassName){
    
var  arrElements  =  (strTagName  ==   " * "   &&  oElm.all) ?  oElm.all :
        oElm.getElementsByTagName(strTagName);
    
var  arrReturnElements  =   new  Array();
    strClassName 
=  strClassName.replace( / \ -/ g,  " \\- " );
    
var  oRegExp  =   new  RegExp( " (^|\\s) "   +  strClassName  +   " (\\s|$) " );
    
var  oElement;
    
for ( var  i = 0 ; i < arrElements.length; i ++ ){
        oElement 
=  arrElements[i];     
        
if (oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    
return  (arrReturnElements)
}




你可能感兴趣的:(getElementByClassName some ways.)