How to Get Attribute in JavaScript: Simple Guide
To get an attribute value from an HTML element in JavaScript, use the
getAttribute method on the element, passing the attribute name as a string. For example, element.getAttribute('href') returns the value of the href attribute.Syntax
The getAttribute method is called on an HTML element to retrieve the value of a specified attribute.
element: The HTML element you want to get the attribute from.attributeName: The name of the attribute as a string.- The method returns the attribute's value as a string, or
nullif the attribute does not exist.
javascript
element.getAttribute(attributeName);
Example
This example shows how to get the href attribute from a link element and display it in the console.
javascript
const link = document.createElement('a'); link.setAttribute('href', 'https://example.com'); const hrefValue = link.getAttribute('href'); console.log(hrefValue);
Output
https://example.com
Common Pitfalls
One common mistake is trying to access attributes directly as properties, which may not always work as expected for custom or non-standard attributes.
Also, getAttribute returns null if the attribute does not exist, so always check for null before using the value.
javascript
/* Wrong way: may not work for all attributes */ const value = element.href; // Works only for standard properties /* Right way: use getAttribute for any attribute */ const value = element.getAttribute('href');
Quick Reference
| Method | Description |
|---|---|
| getAttribute(attributeName) | Returns the value of the specified attribute as a string or null if not present. |
| hasAttribute(attributeName) | Checks if the element has the specified attribute, returns true or false. |
| setAttribute(attributeName, value) | Sets the value of the specified attribute. |
| removeAttribute(attributeName) | Removes the specified attribute from the element. |
Key Takeaways
Use element.getAttribute('attributeName') to get an attribute's value as a string.
getAttribute returns null if the attribute does not exist, so check before use.
Avoid accessing attributes as properties for non-standard or custom attributes.
Use hasAttribute to check if an attribute exists before getting it.
getAttribute works on any attribute, standard or custom.