getElementsByClassName
附上一片关于getElementsByClassName的文章一篇 http://hszy00232.blog.163.com/blog/static/43022753201042051443548/
function getElementsByClassName(oElem, strTagName, strClassName){
var arrElements = (strTagName == '*' && oElem.all) ? oElem.all : oElem.getElementsByTagName(strTagName);
var returnArrElements = new Array();
var oRegExp = new RegExp('(^|\\s)' + strClassName + '($|\\s)');
for(var i=0; i<arrElements.length; i++){
if (oRegExp.test(arrElements[i].className)){
returnArrElements.push(arrElements[i]);
}
}
return (returnArrElements);
}
var arrElements = (strTagName == '*' && oElem.all) ? oElem.all : oElem.getElementsByTagName(strTagName);
var returnArrElements = new Array();
var oRegExp = new RegExp('(^|\\s)' + strClassName + '($|\\s)');
for(var i=0; i<arrElements.length; i++){
if (oRegExp.test(arrElements[i].className)){
returnArrElements.push(arrElements[i]);
}
}
return (returnArrElements);
}
addClass removeClass
function addClass(element, className){
if(!element.className){
element.className = className;
}
else{
element.className+= " "+className;
}
}
function removeClass(element, className){
if (!element) return;
var elementClassName = element.className;
if (elementClassName.length == 0) return;
if(elementClassName == className){
element.className = "";
return;
}
if(elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))){
element.className = elementClassName.replace((new RegExp("(^|\\s)" + className + "(\\s|$)"))," ");
}
}
if(!element.className){
element.className = className;
}
else{
element.className+= " "+className;
}
}
function removeClass(element, className){
if (!element) return;
var elementClassName = element.className;
if (elementClassName.length == 0) return;
if(elementClassName == className){
element.className = "";
return;
}
if(elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))){
element.className = elementClassName.replace((new RegExp("(^|\\s)" + className + "(\\s|$)"))," ");
}
}
数据
var get = {
byId: function(id) {
return document.getElementById(id)
},
byClass: function(sClass, oParent) {
var aClass = [];
var aElem = this.byTagName("*", oParent);
for(var i = 0; i < aElem.length; i++) aElem[i].className == sClass && aClass.push(aElem[i]);
return aClass
},
byTagName: function(elem, obj) {
return (obj || document).getElementsByTagName(elem)
}
};
byId: function(id) {
return document.getElementById(id)
},
byClass: function(sClass, oParent) {
var aClass = [];
var aElem = this.byTagName("*", oParent);
for(var i = 0; i < aElem.length; i++) aElem[i].className == sClass && aClass.push(aElem[i]);
return aClass
},
byTagName: function(elem, obj) {
return (obj || document).getElementsByTagName(elem)
}
};