How to get an attribute from an element in JavaScript
Retrieving attribute values from HTML elements is essential for reading data, checking element states, and building dynamic functionality.
As the creator of CoreUI with over 25 years of JavaScript experience, I regularly use attribute reading for component state management and user interaction handling.
The most effective method is using the getAttribute() method which returns the exact string value stored in the HTML attribute.
This approach provides reliable access to both standard and custom attributes across all browsers.
Use the getAttribute() method to retrieve the value of any HTML attribute from a DOM element.
// Get the element
const button = document.getElementById('submitBtn')
// Read different types of attributes
const isDisabled = button.getAttribute('disabled')
const action = button.getAttribute('data-action')
const ariaLabel = button.getAttribute('aria-label')
const customValue = button.getAttribute('data-user-id')
// Check if attribute exists (returns null if not found)
if (button.getAttribute('data-confirm') !== null) {
console.log('Confirmation required')
}
// Get class attribute
const classes = button.getAttribute('class')
console.log('Element classes:', classes)
The getAttribute() method returns the attribute value as a string, or null if the attribute doesn’t exist. This method retrieves the exact value stored in the HTML, making it perfect for reading data attributes, ARIA attributes, and custom attributes. For boolean attributes like disabled, it returns an empty string if present or null if absent.
Best Practice Note:
This pattern is used extensively in CoreUI components to read configuration data and element states. For standard HTML properties like checked or disabled, consider using direct property access like element.disabled which returns proper boolean values instead of strings.



