JAVASCRIPT
Add, Remove, and Get Element Attributes
Master manipulating HTML element attributes using JavaScript, including setting custom data attributes, removing existing attributes, and retrieving their values dynamically.
const myElement = document.getElementById('someElement');
// Assuming <div id="someElement"></div> exists
myElement.setAttribute('data-custom-id', '12345');
console.log(myElement.getAttribute('data-custom-id')); // Outputs: 12345
myElement.removeAttribute('id'); // Removes the 'id' attribute
console.log(myElement.hasAttribute('id')); // Outputs: false
How it works: This code shows how to interact with HTML element attributes. It selects an element by its ID, adds a new 'data-custom-id' attribute with a value using `setAttribute()`, retrieves that value with `getAttribute()`, removes the original 'id' attribute using `removeAttribute()`, and checks for its existence with `hasAttribute()`.