<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>j</title>
</head>
<body>
<div class="box">
<div class="cute">11111</div>
<div class="hh">aaaa</div>
<div class="hh">bbbb</div>
<div id="test">ccccc</div>
<p>标签名实验</p>
</div>
</body>
<script>
function $(param, obj) {
obj = obj || document;
//根据id名查找元素
if (param[0] === "#")
return document.getElementById(param.slice(1));
// 根据指定类名查找元素
if (param.indexOf(".") === 0)
return getByClass(param.substring(1), obj);
//根据标签名查找
return obj.getElementsByTagName(param);
}
//类名查找元素实现方法
function getByClass(className, obj) {
obj = obj || document;
if (obj.getElementsByClassName)
return obj.getElementsByClassName(className);
var result = [];
var tags = obj.getElementsByTagName("*");
for (var i = 0, len = tags.length; i < len; i++) {
var classNames = tags[i].className.split(" "); // 获取当前遍历元素的类名
for (var j = 0, l = classNames.length; j < l; j++) {
if (className === classNames[j]) { // 找到所需要进行查找的一个元素
result.push(tags[i]);
break;
}
}
}
return result;
}
$("#test").style.background = "red";
$(".hh")[0].style.background = "blue";
$("p")[0].style.background = "green";
</script>
</html>