DOM class name operation classList attribute

The classList attribute returns the class name of the element as a DOMTokenList object.
This attribute is used to add, remove and switch CSS classes in the element.
The classList attribute is read-only, but you can modify it using the add() and remove() methods.

Common method

add(class1, class2, …): Add one or more class names to the element.

document.getElementById("myDIV").classList.add("a");

remove(class1, class2, …): Remove one or more class names in the element.

document.getElementById("myDIV").classList.remove("a");

toggle(class): Switch the class name in the element. That is, if there is this class name, delete this class name, if there is no such class name, add this class name

This element can make it easier for us to write special effects for switching lights, such as:

<!DOCTYPE html>
<html lang="cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .choose {
    
    
            background-color: #000;
        }
    </style>
</head>

<body>
    <button id="btn">开关灯</button>
    <script>
        var btn = document.getElementById('btn')
        btn.onclick = function () {
    
    
            document.body.classList.toggle("choose")
        }

    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/weixin_48549175/article/details/111825773