JavaScript classList and Attributes
Using JavaScript, you can dynamically add, remove, toggle CSS classes, and get/set HTML attributes. This is essential for styling elements and controlling HTML behavior.
1. What is classList?
classList is a read-only property that returns a DOMTokenList (an array-like object) of all the classes of an element. You can use it to add, remove, toggle, or check CSS classes.
Example HTML:
<div id="box" class="square red"></div>
<button onclick="changeClass()">Toggle Class</button>
JavaScript Example:
function changeClass() {
const box = document.getElementById("box");
// Add a class
box.classList.add("blue");
// Remove a class
box.classList.remove("red");
// Toggle a class (add if not present, remove if present)
box.classList.toggle("highlight");
// Check if a class exists
console.log(box.classList.contains("blue")); // true
}
2. Common classList Methods
Method | Description |
---|---|
add("class") | Adds the class |
remove("class") | Removes the class |
toggle("class") | Adds/removes the class |
contains("class") | Checks if the class exists |
replace("old" , "new") | Replaces one class with another |
3. Get and Set HTML Attributes
Use getAttribute() and setAttribute() to read or modify attributes.
Example HTML:
<img id="image" src="pic1.jpg" alt="Picture">
<button onclick="updateImage()">Change Image</button>
JavaScript:
function updateImage() {
const img = document.getElementById("image");
// Get attribute
console.log(img.getAttribute("src")); // "pic1.jpg"
// Set attribute
img.setAttribute("src","pic2.jpg");
img.setAttribute("alt","New Picture");
}
4. Remove or Check Attributes
img.removeAttribute("alt"); // Removes the "alt"
attribute
console.log(img.hasAttribute("src")); // true if "src"
exists
Real-World Use Cases
- Toggling dark/light theme
- Changing form field states (error/success)
- Swapping image src attributes on hover
- Highlighting selected items or tabs