新增获取元素方法:
document.querySelector(" “);单个元素获取
document.querySelectorAll(” "); 多个元素获取
<html>
<body>
<div class = "box box1">box1</div>
<div class = "box box2">box2</div>
<div class = "box box3">box3</div>
</body>
<script>
//获取类名为box1的单个元素
var box1 = document.querySelector(".box1");
box1.style.color = "red";
//获取类名为box的所有元素,返回值为数组
var boxs = document.querySelectorAll(".box");
//循环遍历数组
for(var i=0,i<boxs.length,i++){
boxs[i].innerHTML = "这是box"+i;
boxs[i].style.backgroundColor = "pink";
}
</script>
</html>
新增的类名操作:加、删、判断、切换
加:
box.classList.add(“active”);
删:
box.classList.remove(“active”);
判断:
box.classList.contains(“active”); >>>>返回值是一个布尔值,true or false
切换:
box.classList.toggle(“active”);
<html>
<style>
.box{
width:100px;
height:50px;
background-color:red;
font-size:20px;
}
.active{
background-color:blue;
border-radius:20px;
}
</style>
<body>
<button onclick="addBtn()">增加类名</button>
<button onclick="removeBtn()">删除类名</button>
<button onclick="containsBtn()">判断类名</button>
<button onclick="toggleBtn()">切换类名</button>
<div class="box">Heelo H5</div>
<script>
var box = document.querySelector(".box");
function addBtn(){
box.classList.add("active");
}
function removeBtn(){
box.classList.remove("active");
}
function containsBtn(){
var activeIs = box.classList.contains("active");
if(activeIs){
box.classList.remove("active");
}else{
box.classList.add("active");
}
}
function toggleBtn(){
box.classList.toggle("active");
}
</script>
</body>
</html>