首页 > 代码库 > getElementsByClassName的兼容性
getElementsByClassName的兼容性
/*----------------------------index.html------------------------------------*/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Author" content="Hehe">
<title>Shopping list</title>
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/my_css.css">
</head>
<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don‘t forgrt to buy this stuff.</p>
<ul id="purchases">
<li>A tin of beans</li>
<li class="sale">Cheese</li>
<li class="sale important">Milk</li>
</ul>
<script type="text/javascript" src="http://www.mamicode.com/my_script.js"></script>
</body>
</html>
/*------------------------my_script.js------------------------*/
function getElementsByClassName(node,classname){
if(node.getElementsByClassName){
return node.getElementsByClassName(classname);
}
else{
var results=new Array();
var elems=node.getElementsByTagName("*");
for(var i=0;i<elems.length;i++){
if(elems[i].className.indexOf(classname)!=-1){
results[results.length]=elems[i];
}
}
return results;
}
}
var shopping=document.getElementById("purchases")
var itsems=getElementsByClassName(shopping,"sale");
for(var i=0;i<itsems.length;i++){
alert(typeof itsems[i]);
}
此时页面显示俩个object的警告框。
getElementsByClassName的兼容性