classList
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 |
The following code retrieves classes by index, using array-style notation.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
p.newclass {
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>
Home
JavaScript Book
DOM
JavaScript Book
DOM
HTMLElement:
- The HTMLElement Members
- element tag name, id, direction, language, hidden disabled information
- addEventListener
- appendChild
- attributes returns a collection containing all of the attributes
- classList
- className
- cloneNode
- createElement
- createTextNode
- dataset
- getAttribute
- getElementsByTagName
- hasAttribute
- innerHTML
- insertAdjacentHTML
- insertBefore
- isSameNode
- outerHTML
- onmouseout
- onmouseover
- querySelectorAll
- removeEventListener