JS - element properties - classlist

revision:


returns the class name(s) of an element.

top

The property returns the CSS classnames of an element (a DOMTokenList).

Syntax:

element.classList : a DOMTokenList; a list of the class names of an element.

property value:

none :

example

Click "Add" to add the "myStyle" class to DIV.

Click "Toggle" to toggle the "myStyle" class to DIV.

I am DIV

            <div>
                <button onclick="firstFunction()">Add</button>
                <p style="font-size: 0.9vw;">Click "Add" to add the "myStyle" class to DIV.</p>
                <button onclick="secondFunction()">Toggle</button>
                <p style="font-size: 0.9vw;">Click "Toggle" to toggle the "myStyle" class to DIV.</p>
                <div id="DIV">
                      <p> I am DIV</p>
                </div>
            </div>
            <style>
                .myStyle{background-color: red; padding: 1vw;}
            </style>
            <script>
                function firstFunction() {
                    const list = document.getElementById("DIV").classList;
                    list.add("myStyle");
                }
                function secondFunction() {
                   document.getElementById("DIV").classList.toggle("myStyle");
                }
            </script>
        

Click "Add" to add multiple classes to myDIV.

I am DIV1.

            <div>
                <button onclick="thirdFunction()">Add</button>
                <p>Click "Add" to add multiple classes to myDIV.</p>
                <div id="DIV1">
                    <p>I am DIV1.</p>
                </div>
            </div>
            <style>
                .style_1 { background-color: coral;  padding: 16px;}
                .anotherClass {text-align: center; font-size: 25px; }
                .thirdClass {text-transform: uppercase; }
            </style>
            <script>
                function thirdFunction() {
                    document.getElementById("DIV1").classList.add("style_1", "anotherClass", "thirdClass");
                }
            </script>