DOM是没有getElementsByClassName功能的,只有getElementsByTagName、getElementsById。(至少IE和FF2还不支持。听说Firefox3有了)
下面是我收集整理的一个例子,用函数模拟 getElementsByClassName 功能。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
//var obj=document.getElementsByClassName("qq");
//var obj=document.getElementsByClassName("qq","DIV");
//var obj=document.getElementsByClassName("qq","DIV",myid);
document.getElementsByClassName = function(){
var tTagName ="*";
if(arguments.length > 1){
tTagName = arguments[1];
}
if(arguments.length > 2){
var pObj = arguments[2]
}
else{
var pObj = document;
}
var objArr = pObj.getElementsByTagName(tTagName);
var tRObj = new Array();
for(var i=0; i<objArr.length; i++){
if(objArr[i].className == arguments[0]){
tRObj.push(objArr[i]);
}
}
return tRObj;
}
function test(){
var obj=document.getElementsByClassName("qq");
for (var i=0;i<obj.length;i++){
obj[i].style.color="#ff0000";
}
}
function test2(){
var obj=document.getElementsByClassName("qq","DIV");
for (var i=0;i<obj.length;i++){
obj[i].style.color="#ff0000";
}
}
function test3(){
var myid=document.getElementById('ok');
var obj=document.getElementsByClassName("qq","DIV",myid);
for (var i=0;i<obj.length;i++){
obj[i].style.color="#ff0000";
}
}
</script>
<style type="text/css">
<!--
.qq,.ee { font-size: 14px; border:1px solid #ccc; margin:10px; padding:5px;font-weight:bold;}
#ok,#ttt {border:1px solid #666; margin:15px;}
-->
</style>
</head>
<body>
<input type="button" name="button" id="button" value="所有class为qq的元素" onclick="test()" />
<br />
<input type="button" name="button" id="button" value="所有div里的class为qq的元素" onclick="test2()" />
<br />
<input type="button" name="button" id="button" value="无素OK中的div里的class为qq的元素" onclick="test3()" />
<div id="ttt">
<div class="ee" >Class="ee"</div>
<div class="qq" >Class="qq"</div>
<div class="qq" >Class="qq"</div>
</div>
<div id="ok">
id="ok"
<div class="ee" >Class="ee"</div>
<p class="qq">Class="qq",但是标签为P</p>
<div class="qq">Class="qq"</div>
<div class="qq" >Class="qq"</div>
</div>
</body>
</html>
其根据JS写的一个方法