JAVASCRIPT

Manipulate Element Attributes (Set, Get, Remove)

Learn to dynamically add, read, and delete standard or custom HTML attributes on any DOM element using `setAttribute`, `getAttribute`, and `removeAttribute` for flexible UI.

// Assume an HTML element exists: <button id="myButton">Click Me</button>
const myButton = document.getElementById('myButton');

// 1. Set an attribute
myButton.setAttribute('data-action', 'submit');
myButton.setAttribute('aria-label', 'Submit Form');
console.log('Attribute set:', myButton.outerHTML);

// 2. Get an attribute
const action = myButton.getAttribute('data-action');
console.log('Retrieved data-action:', action); // Output: submit

// 3. Check for existence
const hasAriaLabel = myButton.hasAttribute('aria-label');
console.log('Has aria-label?', hasAriaLabel); // Output: true

// 4. Remove an attribute
myButton.removeAttribute('aria-label');
console.log('Attribute removed:', myButton.outerHTML);

// After removal
const afterRemoval = myButton.getAttribute('aria-label');
console.log('Aria-label after removal:', afterRemoval); // Output: null
How it works: This snippet demonstrates fundamental DOM attribute manipulation. `setAttribute()` adds or updates an attribute's value. `getAttribute()` retrieves an attribute's current value. `hasAttribute()` checks for an attribute's presence, and `removeAttribute()` completely removes it from the element. These methods are crucial for dynamically controlling element behavior, data, and accessibility in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs