Skip to main content

HTML DOM classList Property in JAVA SCRIPT

Definition and Usage..
The classList property returns the class name(s) of an element, as a DOMTokenList object.
This property is useful to add, remove and toggle CSS classes on an element.
The classList property is read-only, however, you can modify it by using the add() and remove() methods.
Cross-browser solution: The classList property is not supported in IE9 and earlier. However, you can use the className property or regular expressions for a cross-browser solution.
Syntax: element.classList
Different types of way how to define classList Property in program.
CODING:
<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
    width: 500px;
    height: 50px;
    padding: 15px;
    border: 1px solid black;
}

.anotherClass {
    background-color: coral;
    color: white;
}

.thirdClass {
    text-transform: uppercase;
    text-align: center;
    font-size: 25px;
}
</style>
</head>
<body>
<div id="div1">I am a DIV element</div>
<button onclick="add()">add class in div tag</button>
<div id="div2" class="mystyle anotherClass thirdClass">I am a DIV element</div>
<button onclick="remove()">remove class in div tag</button>
<button onclick="addRomovclass()">Add Romove class</button>
<button id="div2" onclick="length()">Div Tag property</button>
<script>
function add() {
    document.getElementById("div1").classList.add("mystyle", "anotherClass", "thirdClass");
}
function remove() {
    document.getElementById("div2").classList.remove("mystyle");
}
function length() {
 var x=document.getElementById("div2").classList;
 alert("class names:"+x+"\nNumber of class:"+x.length+"\nLast Class:"+x.item(x.length-1)+"\ncontain mystyle:"+x.contains("mystyle"));
}
function addRomovclass() {
    document.getElementById("div2").classList.toggle("mystyle");
}
</script>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and earlier versions.</p>
</body>
</html>

Comments