JAVASCRIPT
Toggle and Manipulate CSS Classes and Attributes
Master adding, removing, and toggling CSS classes with `classList` and efficiently managing custom data attributes or standard HTML attributes on DOM elements.
function manipulateElementClassesAndAttributes(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
// Add a class
element.classList.add('highlight');
console.log('Added class "highlight":', element.className);
// Remove a class
element.classList.remove('default-style');
console.log('Removed class "default-style":', element.className);
// Toggle a class (add if not present, remove if present)
element.classList.toggle('active');
console.log('Toggled class "active":', element.className);
// Check if a class exists
const hasHighlight = element.classList.contains('highlight');
console.log('Has class "highlight"?', hasHighlight);
// Set a standard attribute
element.setAttribute('data-status', 'pending');
console.log('Set data-status attribute:', element.getAttribute('data-status'));
// Get a data attribute (using dataset API)
element.dataset.itemId = '12345'; // Sets data-item-id="12345"
console.log('Get data-item-id:', element.dataset.itemId);
// Remove an attribute
element.removeAttribute('title');
console.log('Removed title attribute.');
}
// Example Usage:
// Assuming an element like: <div id="myElement" class="default-style" title="Tooltip"></div>
// Call it after the DOM is loaded:
// manipulateElementClassesAndAttributes('myElement');
How it works: This snippet demonstrates powerful ways to control an element's appearance and data using its classes and attributes. `classList` offers convenient methods for managing CSS classes, enabling dynamic styling. The `setAttribute`, `getAttribute`, `removeAttribute` methods handle general HTML attributes, while `dataset` provides a cleaner API for custom `data-*` attributes.