<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<style>
.yelColor{background:yellow;}
</style>
</head>
<body>
<table>
<tr>
<td class="test">11</td>
<td class="test">22</td>
</tr>
<tr>
<td>33</td>
<td class="test">44</td>
</tr>
</table>
<script>
//第一种方法
var tds=document.getElementsByTagName("td");
for(var i=0,len=tds.length;i<len;i++){
if(tds[i].className=="test"){
tds[i].className="yelColor";
// tds[i].setAttribute("class","yelColor");
}
}
//第二种方法(更好,因为每个元素的className不止有test的情况下可以用 第二种)
var tds=document.getElementsByTagName("td");
for(var i=0,len=tds.length;i<len;i++){
if(tds[i].className.indexOf("test")!=-1){
tds[i].className="yelColor";
}
}
/*
if(-1){alert("true");}为真(即使是负数),只有if(0)才为false
*/
//第三种方法(jquery)
$("document").ready(function(){
$('td.test').addClass('yelColor');
});
//错误的方法
var tds=document.getElementsByClassName("test");
for(var i=0,len=tds.length;i<len;i++){
tds[i].setAttribute("class","yelColor");
}
/*
因为每次循环都会从DOM树种重新查找对应的元素。
1.当i=0时,len=3,tds[0]=11,tds[1]=22,tds[2]=44
2.当i=1时,len=2,tds[0]=22,tds[1]=44
3.当i=2时,len=1,tds[0]=44,(此时会报错Uncaught TypeError: Cannot read property 'setAttribute' of undefined)
*/
</script>
</body>
</html>
用js将文档中className有“test”的id标签背景颜色设为黄色
最新推荐文章于 2023-07-12 12:01:55 发布