<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>addclass,removeclass,hasclass,toggleclass,getbyclass</title>
</head>
<body>
<div class="div1" id="box1"></div>
<input type="button" value="按钮" id="btn1"/>
<script>
function addClass(obj,cls) {//obj:要添加classname的元素,cls:要添加的classname;
//如果原来没有class:
if(obj.className == ''){
obj.className = cls;
} else {
//本来已经有class,新增class的情况:
var arrclassname = obj.className.split(' ');//
var index = arrIndexOf(arrclassname,cls);
if(index == -1) {
//如果要添加的class在原来的元素上不存在:
obj.className += ' ' + cls;
}
}
} function arrIndexOf(arr,v){//检测数组中是否有相同的值存在,并且返回它的位置;
for(var i=0;i<arr.length;i++){
if(arr[i] == v){
return i;
}
}
return -1;
} function removeClass(obj,cls){
//如果有class的话:
if(obj.className != ''){
var arrClassName = obj.className.split(' ');//对原有class进行拆分,看看是否包含需要移除的class,也就是传参cls的classname;
var index = arrIndexOf(arrClassName,cls);
//r如果有需要移除的class
if(index != -1){
arrClassName.splice(index,1);
obj.className = arrClassName.join('');
}
}
} function hasClass(obj,cls){
var cls = cls || '';
if( cls.replace(/\s/g,'').length == 0){
return false;//当cls没有参数时,返回false;
}else{
return new RegExp(' ' + cls + '').test(' ' + obj.className);
}
} function toggleClass(obj,cls){
hasClass(obj,cls) ? removeClass(obj,cls) : addClass(obj,cls);
} function getByClass(oParent, sClass) {
if (oParent.getElementsByClassName) {
return oParent.getElementsByClassName(sClass);
} else { //IE 8 7 6
var arr = [];
var reg = new RegExp('\\b' + sClass + '\\b');
var aEle = oParent.getElementsByTagName('*');
for (var i = 0; i < aEle.length; i++) {
if (reg.test(aEle[i].className)) {
arr.push(aEle[i]);
}
}
return arr;
}
} var oBtn1 = document.getElementById('btn1');
var oBox1 = document.getElementById('box1');
oBtn1.onclick = function () {
if( hasClass(oBox1,'div1') ){
alert('hasclass');
}; alert( getByClass(document,'div1').length );
} </script> </body>
</html>