Javascript DOM HTML Element classList Property

Introduction

The classList property returns the class name(s) of an element, as a DOMTokenList object.

The following code adds the mystyle class to a <div> element:

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

Click the button to add the class to DIV.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//from   www.  j  av a 2s . c o  m
  width: 300px;
  height: 50px;
  background-color: coral;
  color: white;
  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");
}
</script>

</body>
</html>

The classList property returns DOMTokenList, containing a list of the class name(s) of an element.

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

The classList property is read-only.

We can use its method such as the add() and remove().

Methods

Method
Description
add(class1, class2, ...)

Adds one or more class names to an element.
If the specified class already exist, the class will not be added
contains(class)

Returns a Boolean value,
indicating whether an element has the specified class name.
item(index)

Returns the class name with a specified index number from an element.
Index starts at 0.Returns null if the index is out of range
remove(class1, class2, ...)
Removes one or more class names from an element.
toggle(class, true|false)





Toggles between a class name for an element.
If the class does not exist, it is added to the element, and the return value is true.
The optional second parameter is a Boolean value that forces the class to be added or removed, regardless of whether or not it already existed.
For example:
Remove a class: element.classList.toggle("class-To-Remove", false);
Add a class: element.classList.toggle("class-To-Add", true);



PreviousNext

Related