JAVASCRIPT

Manage Element Attributes and CSS Classes

Discover JavaScript methods to efficiently add, remove, and toggle CSS classes, along with setting and getting custom data attributes on HTML elements.

const myElement = document.getElementById('target-element');

// Add a class
myElement.classList.add('active');

// Remove a class
myElement.classList.remove('inactive');

// Toggle a class (add if not present, remove if present)
myElement.classList.toggle('highlight');

// Check if a class exists
const hasActive = myElement.classList.contains('active'); // true or false

// Set a custom data attribute
myElement.setAttribute('data-item-id', '456');

// Get a custom data attribute
const itemId = myElement.getAttribute('data-item-id'); // '456'

// Remove an attribute
// myElement.removeAttribute('data-item-id');
How it works: This code illustrates how to manipulate an element's attributes and CSS classes. The `classList` property provides methods like `add()`, `remove()`, `toggle()`, and `contains()` for easy management of an element's CSS classes. For generic attributes, `setAttribute()` allows you to add or change an attribute's value, `getAttribute()` retrieves its current value, and `removeAttribute()` deletes it from the element. Data attributes (e.g., `data-item-id`) are commonly used to store custom data directly on HTML elements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs