CoreUI ONE — 250+ PRO components and 25+ admin templates for React, Angular, Vue, Bootstrap and Next.js, plus Data Grid, Scheduler, 4,300+ PRO icons and the Next.js boilerplate. One license. → See what you get

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. 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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to disable a button in JavaScript
How to disable a button in JavaScript

How to check if a key exists in JavaScript object?
How to check if a key exists in JavaScript object?

How to Migrate from create-react-app to Vite?
How to Migrate from create-react-app to Vite?

How to fix “SyntaxError: Cannot use import statement outside a module”?
How to fix “SyntaxError: Cannot use import statement outside a module”?