Element.prototype.getAttribute
Returns the value of a specified attribute on the element, or null if the attribute does not exist
Syntax
element.getAttribute(name)Parameters
| Parameter | Type | Description |
|---|---|---|
| name | string | The name of the attribute to retrieve |
Return Value
The attribute value as a string, or null
Examples
const link = document.querySelector('a')!
const href = link.getAttribute('href')
console.log(href)const el = document.querySelector('[data-id]')!
const id = el.getAttribute('data-id')
console.log('Data ID:', id)function getRole(el: HTMLElement): string {
return el.getAttribute('role') || 'none'
}Understanding Element.prototype.getAttribute
The Element.prototype.getAttribute method in JavaScript returns the value of a specified attribute on the element, or null if the attribute does not exist. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.
The method signature is element.getAttribute(name). It accepts 1 parameter: name. When called, it returns the attribute value as a string, or null. Understanding when and how to use getAttribute() helps you write more expressive, readable code.
Common use cases for Element.prototype.getAttribute include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-setattribute, dom-hasattribute, dom-removeattribute, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.prototype.getAttribute is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Element.prototype.setAttributeSets the value of an attribute on the specified element, adding it if it does not already exist
Element.prototype.hasAttributeReturns a boolean value indicating whether the specified element has the specified attribute or not
Element.prototype.removeAttributeRemoves the attribute with the specified name from the element
More Element Methods
Other methods in the Element object
Related Tools
More Element Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.