Element classList Property - Javascript DOM

Javascript examples for DOM:Element classList

Description

The classList property returns the class names of an element, as a DOMTokenList object.

This property is useful to add, remove and toggle CSS classes on an element.

Properties

Property Description
length Returns the number of classes in the list. This property is read-only

Return Value

A DOMTokenList, containing a list of the class name(s) of an element

The following code shows how to Add the "mystyle" class to a <div> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//from w  ww . j  a  v  a2 s.c o m
    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>

<button onclick="myFunction()">Test</button>

<div id="myDIV">
I am a DIV element
</div>

<script>
function myFunction() {
    document.getElementById("myDIV").classList.add("mystyle", "anotherClass", "thirdClass");
}
</script>

</body>
</html>

Related Tutorials