JAVASCRIPT

Manipulating HTML Attributes and Data Attributes

Understand how to get, set, and remove standard HTML attributes and custom `data-*` attributes on DOM elements using JavaScript.

document.getElementById('image-button').addEventListener('click', function() {
  const myImage = document.getElementById('my-image');
  
  // Get a standard attribute
  const currentSrc = myImage.getAttribute('src');
  console.log('Current Image Source:', currentSrc);

  // Set a standard attribute
  const newSrc = 'https://via.placeholder.com/150/FF0000/FFFFFF?text=NewImage';
  myImage.setAttribute('src', newSrc);
  myImage.setAttribute('alt', 'A dynamically set new image');
  console.log('Image source updated to:', newSrc);

  // Get a data attribute
  const originalSize = myImage.dataset.originalSize; // Accesses data-original-size
  console.log('Original Size from Data Attribute:', originalSize);

  // Set a data attribute
  myImage.dataset.status = 'loaded'; // Sets data-status='loaded'
  console.log('Image status data attribute set to:', myImage.dataset.status);

  // Remove an attribute (standard or data)
  myImage.removeAttribute('title'); // Removes the title attribute
  console.log('Title attribute removed.');

  // Check if an attribute exists
  if (myImage.hasAttribute('data-author')) {
    console.log('Data-author exists:', myImage.getAttribute('data-author'));
  } else {
    console.log('Data-author does not exist.');
  }
});

/*
HTML structure for demonstration:
<img id="my-image" src="https://via.placeholder.com/150/0000FF/FFFFFF?text=Original" 
     alt="Original placeholder image" title="Click to change" 
     data-original-size="150x150" data-author="Jane Doe" style="border: 1px solid #ccc;">
<button id="image-button">Manipulate Image Attributes</button>
*/
How it works: This snippet demonstrates how to interact with HTML attributes and custom `data-*` attributes using JavaScript. `element.getAttribute()` retrieves the value of an attribute, while `element.setAttribute()` sets or updates it. `element.removeAttribute()` completely removes an attribute. For `data-*` attributes, the convenient `element.dataset` property provides direct access, where `data-original-size` becomes `dataset.originalSize`. This is crucial for dynamically changing element behavior, styling, or storing custom, non-visual data directly on the DOM element for JavaScript logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs