标签:
/*兼容低版本浏览器的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;
}
}
兼容低版本浏览器的getElementByClassName方法
标签:
原文地址:http://www.cnblogs.com/Eyrum/p/4609821.html