Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.one {
width:300px;
height:300px;
background-color:red;
}
</style>
</head>
<body>
<div class="one">hhhhhhhhh</div>
<div class="one three">eeeeeeeeeeee</div>
<div class="one two">llllllllllllll</div>
<div class="one two three">pppppppppppp</div>
<h3 class="one">11111111111111</h3>
<h3>2222222222222</h3>
<p class="one">33333333333333</p>
</body>
</html>
<script>
var ones = gclass("one");
console.log(ones);
for(var i = 0; i < ones.length; i++) {
ones[i].style.backgroundColor = "green";
}
// 通过类名获取所有元素的方法
function gclass(className, tagName) {
// var alltags = document.all;
var alltags = document.getElementsByTagName(tagName || "*");
var arr = new Array();
for(let i = 0; i < alltags.length; i++) {
// one two
// split把一个字符串分割成字符串数组:
var one = className.split(" ");
var two = alltags[i].className.split(" ");
if(isHasArray(one, two)) {
arr[arr.length] = alltags[i];
}
}
//返回所有类元素集合
return arr;
}
// 判断一个数组中的所有元素是否在另外的一个数组中存在
function isHasArray(one, two) {
if(two.length < one.length){
return false;
}
var flag = 0;
for(let i=0; i<one.length; i++) {
for(let j=0; j<two.length; j++) {
if(one[i]==two[j]){
flag++;
break;
}
}
}
return flag == one.length;
}
</script>
结果展示