classList属性

1)知识梳理

classList 是H5新增的一个属性

作用:获取 添加 删除 切换CSS类

添加 删除 切换 等的使用 需要先获取到

2)返回值

返回一个数组
DOMTokenList(3) ["one", "two", "three", value: "one two three"] 0: "one" 1: "two" 2: "three" length: 3 value: "one two three" __proto__: DOMTokenList

3)代码范例

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>classList</title>
    <style>
        .red { background: black; }
    </style>
</head>
<body>
<div class="one two three"></div>
<button>开关灯</button>
<script>
    var div = document.querySelector('div');
    var btn = document.querySelector('button');
    //1 获取类名
    console.log(div.classList);//返回一个数组
    console.log(div.classList[0]);//取得第一个元素

    //2 添加类名 是追加的形式 不会覆盖前面的
    div.classList.add('five');
    
    //3 删除类名
    div.classList.remove('five');

    //4 toggle 切换类名 [如果有 我删除 如果没有 我添加]
    btn.onclick = function(){
        document.body.classList.toggle('red');
    }
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/fuyunlin/p/14475053.html