<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
li{
width: 100%;
height: 20px;
}
</style>
<body>
<li>li+1</li>
<li>li+2</li>
<li>li+3</li>
<li>li+4</li>
<li>li+5</li>
<script>
var li=document.querySelectorAll('li');
for(var i=0;i<li.length;i++){
if(i%2==0){
li[i].style.backgroundColor='green'
}
else{
li[i].style.backgroundColor='red'
}
}
</script>
</body>
</html>
设置<li></li>等标签时使用document.querySelectorAll()方法可以将所有li的对象返回
运行结果如下
使用document.querySelector()只可以返回所遇到的第一个符合条件的标签对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
li{
width: 100%;
height: 20px;
}
</style>
<body>
<li>li+1</li>
<li>li+2</li>
<li>li+3</li>
<li>li+4</li>
<li>li+5</li>
<script>
var li=document.querySelector('li');
li.style.backgroundColor='green'
// for(var i=0;i<li.length;i++){
// if(i%2==0){
// li[i].style.backgroundColor='green'
// }
// else{
// li[i].style.backgroundColor='red'
// }
// }
</script>
</body>
</html>
结果rux