zoukankan      html  css  js  c++  java
  • 兼容低版本浏览器的getElementByClassName方法

    /*兼容低版本浏览器的getElementByClassName方法*/
    function getElementsByClassName(root,className){
    	if(root.getElementsByClassName){
    		return root.getElementsByClassName(className);
    	}else{
    		var elements=root.getElementsByTagName();
    		var result=[];
    		for(var i=0,element;element=elements[i];i++){
    			//hasClassName判断元素是否有className属性
    			if(hasClassName(element,className)){
    				result.push(element);
    			}
    		}
    		return result;
    	}
    }
    
    // ----------------------------------------------------------------------------
    // HasClassName
    //
    // Description : returns boolean indicating whether the object has the class name
    //    built with the understanding that there may be multiple classes
    //
    // Arguments:
    //    element              - element to manipulate
    //    className                - class name to add
    //
    function hasClassName(element, className)
       {
     
       // if there is a class
       if ( element.className )
          {
     
          // the classes are just a space separated list, so first get the list
          var arrList = element.className.split(' ');
     
          // get uppercase class for comparison purposes
          var classNameUpper = className.toUpperCase();
     
          // find all instances and remove them
          for ( var i = 0; i < arrList.length; i++ )
             {
     
             // if class found
             if ( arrList[i].toUpperCase() == classNameUpper )
                {
     
                // we found it
                return true;
     
                }
     
             }
     
          }
     
       // if we got here then the class name is not there
       return false;
     
       }


    //----------------------------------------------------------------

    function getElementsByClassName(element, names) {
      if (element.getElementsByClassName) {
        return element.getElementsByClassName(names);
      } else {
        var elements = element.getElementsByTagName('*');
        var result = [];
        var element,
        classNameStr,
        flag;
        names = names.split(' ');
        for (var i = 0; element = elements[i]; i++) {
          classNameStr = ' ' + element.className + ' ';
          flag = true;
          for (var j = 0, name; name = names[j]; j++) {
            if (classNameStr.indexOf(' ' + name + '') == -1) {
              flag = false;
              break;
          }
        }
          if (flag) {
            result.push(element);
          }
      }
       return result;
     }
    }

      

  • 相关阅读:
    第三周作业
    第二周作业
    计算机基础学习心得
    第三次作业
    第2次作业(指针总结)
    2018(上)C高级第0次作业
    本学期最后一次作业 总结。
    第十四、十五周作业
    第七周作业
    第六周作业
  • 原文地址:https://www.cnblogs.com/Eyrum/p/4609821.html
Copyright © 2011-2022 走看看