getElementsByClassName
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<script>
window.onload=function () {
var ul1=document.getElementById('ul1');
var aLi=getElementsByClassName(ul1,'li','box');
console.log(aLi);
function getElementsByClassName(parent,tagName,className) {
var aEls=parent.getElementsByTagName(tagName);
var arr=[];
for (var i = 0; i < aEls.length; i++) {
var aClassName=aEls[i].className.split(' ');
for (var j = 0; j < aClassName.length; j++) {
if (aClassName[j]==className) {
arr.push(aEls[i]);
break;
}
}
}
return arr;
}
}
</script>
<ul id="ul1">
<li>111111</li>
<li class="box box">2222222</li>
<li>3333333</li>
<li class="box box2">444444</li>
</ul>
</body>
</html>
addclassname
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>class</title>
<style>
</style>
</head>
<body>
<div id="div1" >
</div>
<script>
window.onload=function () {
var odiv=document.getElementById('div1');
addclass(odiv,'box3');
function addclass(obj,className) {
if (!obj.className) {
obj.className=className;
}
else {
var arrClassName=obj.className.split(' ');
var _index=arrIndexOf(arrClassName,className);
if (_index==-1) {
obj.className+=' '+className;
}
}
}
function removeclass(obj,className) {
if (obj.className) {
var arrClassName=obj.className.split(' ');
var _index=arrIndexOf(arrClassName,className);
if (_index!=-1) {
arrClassName.splice(_index, 1)
obj.className=arrClassName.join(' ');
}
}
}
removeclass(odiv,'box');
function arrIndexOf(arr,v) {
for (var i = 0; i < arr.length; i++) {
if (arr[i]==v) {
return i;
}
}
return -1;
}
}
</script>
</body>
</html>