JAVASCRIPT

Update Element Attributes and CSS Classes

Discover how to programmatically change HTML attributes like `src`, `href`, `data-*` and manipulate an element's CSS classes using JavaScript DOM methods.

// Assume an HTML element like: <img id="myImage" src="old.jpg" alt="Old Image">
const imageElement = document.getElementById('myImage');

if (imageElement) {
    // Change src attribute
    imageElement.setAttribute('src', 'new-image.png');
    // Change alt attribute
    imageElement.alt = 'New Dynamic Image';
    // Add a data attribute
    imageElement.dataset.imageId = '12345'; // Accesses data-image-id

    // Manipulate classes
    imageElement.classList.add('fade-in');
    imageElement.classList.remove('loading');
    imageElement.classList.toggle('active'); // Toggles 'active' class
    
    console.log('Image attributes and classes updated.');
    console.log('Current classes:', imageElement.classList.value);
    console.log('Data Image ID:', imageElement.dataset.imageId);
} else {
    console.log('Image element with ID "myImage" not found.');
}
How it works: This code snippet illustrates various ways to modify an existing DOM element's attributes and CSS classes. It uses `setAttribute` and direct property access (`.alt`) to change attributes. The `dataset` property is used for `data-*` attributes. `classList` offers convenient methods like `add`, `remove`, and `toggle` to manage an element's CSS classes without directly manipulating the `className` string.

Need help integrating this into your project?

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

Hire DigitalCodeLabs