How to set an attribute on an element in JavaScript
Setting attributes on HTML elements dynamically is fundamental for creating interactive web applications and manipulating DOM elements.
With over 25 years of JavaScript development experience and as the creator of CoreUI, I’ve used attribute manipulation extensively in building dynamic UI components.
The most reliable method is using the setAttribute() method which works consistently across all browsers and attribute types.
This approach provides precise control over element properties and ensures proper HTML structure.
Use the setAttribute() method to add or update any HTML attribute on a DOM element.
// Get the element
const button = document.getElementById('myButton')
// Set different types of attributes
button.setAttribute('disabled', '')
button.setAttribute('data-action', 'submit')
button.setAttribute('aria-label', 'Submit form')
button.setAttribute('class', 'btn btn-primary')
// Set custom attributes for data storage
const userCard = document.querySelector('.user-card')
userCard.setAttribute('data-user-id', '12345')
userCard.setAttribute('data-role', 'admin')
The setAttribute() method takes two parameters: the attribute name and its value. For boolean attributes like disabled or readonly, you can pass an empty string as the value. The method works with standard HTML attributes, data attributes, ARIA attributes, and custom attributes. It will create the attribute if it doesn’t exist or update its value if it does.
Best Practice Note:
This is the same approach used throughout CoreUI components for dynamic attribute management and accessibility features. For better performance when setting boolean properties, consider using direct property assignment like element.disabled = true instead of setAttribute() for standard HTML properties.



