【H5】标签class类名属性的动态修改方法:
box.classList.add(“className”); //添加类名
box.classList.remove(“className”); //删除属性
box.classList.toggle(‘className’); //转换属性:class类名有className就删除 没有就加上
box.classList.contains(‘className’); //查询属性:有返回true/没有返回false
实现代码如下:
<!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>
<body>
<div id="box" class="aaa"></div>
<input type="button" value="添加">
<input type="button" value="删除">
<input type="button" value="获取">
<input type="button" value="切换">
<input type="button" value="判断">
<script>
let inp = document.getElementsByTagName('input');
const box = document.getElementById('box');
inp[0].onclick = function(){
//remove:添加lixiang类名
box.classList.add("wangdasha","lixiang");
console.log(box.classList)
}
inp[1].onclick = function(){
//remove:删除lixiang类名
box.classList.remove("lixiang");
console.log(box.classList)
}
inp[2].onclick = function(){
console.log( box.classList.length )
console.log(box.classList)
}
inp[3].onclick = function(){
//toggle转换:class类名有hashiqi就删除 没有就加上
box.classList.toggle('hashiqi')
console.log(box.classList)
}
inp[4].onclick = function(){
//contains:判断有无hashiqi类名
//box.classList.contains() 返回布尔值;
console.log(box.classList.contains('hashiqi'))
}
</script>
</body>
</html>
box.dataset //方法获取属性
box.removeAttribute (); //删除属性
<!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>
<body>
<div id='box' data-panfu='panfu' pandi='pandi' data-xiaoHuiHui='huihui' data-hans='hanS'></div>
<script>
// dataset : 数据集 主要用于传输数据;拿取属性不区分大小写。
const box = document.getElementById('box');
console.log( box.dataset.panfu ) //获取属性方法
console.log( box.dataset.hans )
console.log( box.dataset["hans"] ) //获取属性方法
console.log( box.dataset["xiaohuihui"] )
// console.log( box )
box.removeAttribute('pandi'); //删除自定义属性
box.removeAttribute('data-panfu'); //删除自定义data属性
// console.log( box )
//delete box.dataset['data-xiaohuihui'] //错误写法
delete box.dataset['xiaohuihui'] //正确写法;
console.log( box.dataset["xiaohuihui"] )
// console.log( box )
</script>
</body>
</html>