自定义byClassName
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/*
node.getElementByClassName()
*/
function elementByClassName(node,classStr){
//1.获取node这个节点下所有的子节点
var nodes = node.getElementsByTagName("*");
var arr = [];
for(var i=0;i<nodes.length;i++){
if(nodes[i].className === classStr){
arr.push(nodes[i]);
}
}
return arr;
}
window.onload = function(){
var oL = document.getElementById("ol1");
var nodes = elementByClassName(oL,"box")
alert(nodes.length);
for(var i=0;i<nodes.length;i++){
nodes[i].style.backgroundColor = 'red';
}
}
</script>
</head>
<body>
<ul id = 'ul1'>
<li>111</li>
<li class='box'>111</li>
<li class='box'>111</li>
<li name='hello'>111</li>
<li>111</li>
<li>111</li>
<div class='box' name='hello'>111</div>
</ul>
<input type="text" name='hello'/>
<br>
<span name='hello'>111</span>
<ol id = 'ol1'>
<li class='box'>111</li>
<li class='box'>111</li>
<li>111</li>
<li>111</li>
<li>111</li>
<li>111</li>
</ol>
</body>
</html>
运行结果: