How to get and manage the class list for a HTML element in Javascript
Class list
classList
property returns a
DOMTokenList
object.
DOMTokenList
defines methods and properties
that allow you to manage the class list.
Member | Description | Returns |
---|---|---|
add(class) | Adds the specified class to the element | void |
contains(class) | Returns true if the element belongs to the specified class | boolean |
length | Returns the number of classes to which the element belongs | number |
remove(class) | Removes the specified class from the element | boid |
toggle(class) | Adds the class if it is not present and removes it if it is present | boolean |
Example
The following code retrieves classes by index, using array-style notation.
<!DOCTYPE HTML>
<html>
<head>
<style>
p.newclass { <!-- w w w . j av a 2 s. c o m-->
background-color: grey;
color: white;
}
</style>
</head>
<body>
<p id="textblock" class="existing">
this is a test.
</p>
<pre id="results"></pre>
<button id="toggle">Toggle Class</button>
<script>
var results = document.getElementById("results");
document.getElementById("toggle").onclick = toggleClass;
listClasses();
function listClasses() {
var classlist = document.getElementById("textblock").classList;
results.innerHTML = "Current classes: "
for (var i = 0; i < classlist.length; i++) {
results.innerHTML += classlist[i] + " ";
}
}
function toggleClass() {
document.getElementById("textblock").classList.toggle("newclass");
listClasses();
}
</script>
</body>
</html>